Get values from TEXTAREA - javascript

<textarea name="test" id="text">
text
area
one one
two
break above
last
</textarea>
<span id="getvalues">get values</span>
$("#getvalues").click(function(){
})
How can i get all values from this textarea from each line to javascript array?
This should:
ignore whitespace - trim
ignore white break
Next i would like make:
$.each(textareavalues, function(index, value) {
console.log('#' + value + '#');
});
This should show me:
#text#
#area#
#one one#
#two#
#break above#
#last#
LIVE EXAMPLE: http://jsfiddle.net/BW8Z2/1/

When you say "ignore white space - trim", you mean "ignore leading and trailing white space on a line, but keep internal white space"? And "ignore white break" means "ignore lines with just white space"?
Something like this:
$("#getvalues").click(function(){
var lines = $("#text").val()
.replace(/\n\s*\n/g,"\n")
.replace(/^\s+|\s+$/gm,"")
.split(/\n/);
$.each(lines, function(i, val) {
console.log("#" + val + "#");
});
})

$("#getvalues").click(function(){
var $textareavalues = $("#text").val();
var x = $textareavalues.split('\n');
$.each(x, function(index, value) {
var text = $.trim(value);
if(text !== "")
console.log('#' + text + '#');
});
});

This will get you started:
var textareavalues = $('textarea').val().split('\n');
you can find how to trim strings and how to exclude empty items in an array in JavaScript from other questions on StackOverflow.

Related

extract text from html without loosing new lines

I use the following code to extract text from html.
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>"
var text = extractContent(html);
console.log("TEXT: " + text);
function extractContent(s) {
var span = document.createElement('span');
span.innerHTML = s;
return span.textContent || span.innerText;
}
the result of this code is the text without new lines. but I want the result to replace divs with "\n" like this:
first line."\n"second line. "\n" third line."\n"
Use s.replaceAll('&nbsp', '\\n'); to replace the linefeed.
Note: The backslash \ needs to be escaped with another \.
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>"
var text = extractContent(html);
console.log("TEXT: " + text);
function extractContent(s) {
var span = document.createElement('span');
s = s.replaceAll('&nbsp', '\\n');
span.innerHTML = s;
return span.textContent || span.innerText;
}
document.createElement is not necessary, you can use regexp alone to achieve this:
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>"
var text = extractContent(html);
console.log("TEXT: " + text);
function extractContent(s) {
/*
* /(<[^>]+>)+/gim <---- this regexp to match all html tags and replace them with \n,
* also merge empty content html tags into one \n
*
*/
return s.replace(/(<[^>]+>)+/gim, "\n");
}

How to add a new line to HTML text using JavaScript?

I am using this code which essentially types text onto the screen. I am unsure how to add a new line to the string which is being displayed.
I have already tried \n for those posting their answers. This does NOT work. A new line is not started in my HTML
Code:
var myString = "public class MyResume implements Resume{" +
/*this is where I want the new line*/ "...." ;
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += myArray.shift();
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
<div id="myTypingText"></div>
You can also use <br>.Just like"your string.<br> new line"
Here's an overly simplistic approach with full code. Use a tilde ~ and then watch for it in your frameLooper to insert a like this:
<html>
<body>
<div id="myTypingText"></div>
<script>
var myString = 'public class MyResume implements Resume{~....' ;
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
var char = myArray.shift();
if (char === '~')
{ document.getElementById("myTypingText").innerHTML += '<br/>'; }
else
{ document.getElementById("myTypingText").innerHTML += char; }
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
</body>
</html>
Simply adding <br> to myString doesn't work because you're inserting each character at one time. When a character gets added with innerHTML, JavaScript encodes it:
$('element').innerHTML += "<";
> "string<"
If you did this for each character in <br>, you'd end up with
>"string<br<"
You need some way to tell your script to add the entire element when you reach a "break character". You could use an uncommon character like a pipe | or you could add a method which looks ahead to make sure that the next few characters don't spell out <br>.
To add string to a new line, you need the \n in your string. For example:
var string = 'This is the first line \nThis is the second line'
console.log(string)
This would output
This is the first line
This is the second line
Why don't you just append ul>li or p to your text, something like this:
document.getElementById("myTypingText").innerHTML += "<p>" + myArray.shift() "</p>";
or
document.getElementById("myTypingText").innerHTML += "<li>" + myArray.shift() "</li>";
with:
<ul id="myTypingText"></ul>

Replace selected text inside p tag

I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?
You can simply do $("#1-pagedata").html('New text here');
Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));

Generated HTML by javascript is not formatted correctly

I want to make a input field where I can search for friends in a list, these friends I retrieve from a xml file and I generate them using javascript
The code I generate this with:
friendListInDiv = document.createElement("p");
var link = document.createElement("a");
link.onclick = function() {
openChat(friendsXML[i].textContent)
};
var friendText = document
.createTextNode(friendsXML[i].textContent + ":"
+ statusXML[i].textContent);
link.appendChild(friendText);
friendListInDiv.appendChild(link);
friendDiv.appendChild(friendListInDiv);
Now the problem I'm facing I have demonstrated in a jsfiddle:
https://jsfiddle.net/x897pv9o/
As you can see if you type in "j" in the top input bar it hides all friends but type "j" in the bottom one it will still display "Joske"
This is because these tags
<div id="friendlist"><p><a>
Joske:
Offline</a></p><p><a>
Tom:
Offline</a></p><p><a>
Dirk:
Offline</a></p></div>
are not being formatted correctly, how can I make them format correctly?
As Shaunak D mentioned in a comment, you can use .trim() to remove preceding and trailing whitespace, including new lines, from text. You can either use this on your text content when creating the node, or use it in your search function to exclude new lines.
In document.createTextNode:
var friendText = document.createTextNode(
friendsXML[i].textContent.trim() + ":" + statusXML[i].textContent);
In $('#searchinfriend').keyup:
$('#searchinfriend').keyup(function () {
var valThis = $(this).val().toLowerCase();
$('#friendlist p a').each(function () {
var text = $(this).text().trim().toLowerCase();
(text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();
});
});

How do I add an incrementing ID for each sentence in a paragraph?

I was able to replace the punctuation with span tags and separate the sentences, but I tried to increment the id by one for each sentence and it only worked on the first one.
$('.whatever').each(function(index) {
var sentences = $(this).html().replace(/([^.!?]*[^.!?\s][.!?]['"]?)(\s|$)/g,
'<span id="'+index+'">$1</span>$2<SENTENCE_END>');
$(this).html(sentences);
});
Thanks for any ideas.
If all of your text is inside #whatever, you'll want to first split the text by periods and then iterate through each of those to add <spans>.
Here's an example:
// set counter
var j = 0;
// get text from div
var sentences = $('#whatever').text().trim();
// split text by "."
var sentences = sentences.split('.');
// empty the output div
$('#whatever').empty();
// for each sentence, check for blank sentence,
// add span with counter number, trim spaces,
// add leading space if this is not the first sentence,
// add "." at the end of sentence, output to div
$(sentences).each(function () {
if (this.trim()!='') {
$('#whatever').append( (j>0?" ":"") + '<span class="sentence" id="sentence_' + j + '">' + this.trim() + '.</span>');
j++;
}
});
http://jsfiddle.net/FrDzL/1/
Why are you using the id selector? The id selector $('#whatever') only selects one element (the first element matching the id on the page). Hence that each loop is only executed once (that's why it only worked in the first one).
Modify your html code to use classes, and select using $('.whatever').
ID Selector (“#id”)
Selects a single element with the given id attribute.
Source: http://api.jquery.com/id-selector/
Try the following
HTML
<p class="whatever">hej</p>
<br>
<p class="whatever">hej</p>
<br>
<p class="whatever">hej</p>
JS
var j = 0;
$('.whatever').each(function() {
var sentences = $(this).html().replace('hej','nej');
j++;
$(this).html(sentences);
});
JSFiddle
And finally, working code for your example
var j = 0;
$('.whatever').each(function() {
var sentences = $(this).html().replace(/([^.!?]*[^.!?\s][.!?]['"]?)(\s|$)/g,
'<span class="sentence" id="'+j+'">$1</span>$2<SENTENCE_END>');
j++;
$(this).html(sentences);
});

Categories

Resources