Cannot split textarea on newline created from html entities - javascript

I have a textarea that needs a default value including new lines so I used the technique employing HTML entities found from this answer
<textarea rows=4 id="mytextarea">John,2
Jane,3
John,4
Jane,5</textarea>
Then I have a button with launches a button for parsing the textarea and the first thing I want to accomplish is creating a rows array from the textarea value but this is where I am having problems. There is another answer that goes into the details of which browsers represent line breaks as \r\n and which as \n only and though this may not be strictly necessary in my case I still decided to try it:
var textAreaValue = document.getElementById("mytextarea").value;
textAreaValue = textAreaValue.replace(/\s/g, ""); //remove white space
var rows = textAreaValue.replace(/\r\n/g, "\n").split("\n");
rows however is coming back as ["John,2Jane,3John,4Jane,5"]. So the split is having no effect; what am I doing wrong?

The \s in your regex is removing the line breaks. Try commenting out that replacement and check your rows value again, it should then be as you expect!
function parseText() {
var textAreaValue = document.getElementById("mytextarea").value;
//textAreaValue = textAreaValue.replace(/\s/g, ""); //remove white space
var rows = textAreaValue.replace(/\r\n/g, "\n").split("\n");
alert(rows);
}
See JSFiddle here: http://jsfiddle.net/xs2619cn/1/
I changed your commas to full stops just to make the alert output clearer.

You don't use \n and \r, so you can splite 
 or
.
var rows = textAreaValue.replace(/(&#[13|10];)+/g, "\n").split("\n");
Demo: http://jsfiddle.net/rr1zvxko/

Related

regex to separate paragraphs by double new line

Making a tiny helper for authors to add/remove empty lines in textarea. The one that removes extra lines seems to work:
if(jQuery("#remove_line").prop("checked")){
conver = conver.replace(/^\s*[\r\n]/gm,'');
}
But there has to be a reverse one that makes any new line into double new line (no matter if there's just 1 or even 3 new lines in a row). E.g. this:
text
text
text
text
Should be processed into this:
text
text
text
text
Anyone can help with that? Thanks in advance!
You can match one or more newlines [\r\n]+ and replace with 2 newlines \n\n
const regex = /[\r\n]+/gm;
const str = `text
text
text
text`;
console.log(str.replace(/[\r\n]+/g, `\n\n`));
didn't test but i think this could work : replace(/[\n]+?/g,'\n\n')
\n+ will match 1 or more new lines, the question mark will force to take the shortest amount possible (this will stop the matching block at the first non new line character)
The reverse?
addEventListener('load', ()=>{
const ta = document.querySelector('textarea');
function doubleSpaceAfter(fullText, text, insensitive = true){
const s = insensitive ? 'i' : '';
return fullText.replace(new RegExp('('+text+')\\s+', 'g'+s), '\n\n$1\n\n');
}
ta.value = doubleSpaceAfter(ta.value, 'text here');
}); // end load
<textarea>other stuff text here is this what you want? text here text here</textarea>

Line break javascript doesn't insert new line "\n"

I've been trying to wrap my head around this whole line break thing, and I've searched and researched my soul out here. I can't seem to find an answer to my specific problem here. I want to fetch the input from a textarea and put it in an array with new lines. All it does is put a comma between the words, and it seems it only adds multiple commas to where the line breaks are supposed to be. When I add < br / >, all it does is exclude the letter b from the text.
function Wordscount() {
var pText = document.getElementById("myTextarea").value.split(/[\n <>.,\?]/);
document.getElementById("text").innerHTML = pText;
It basically just looks like this when I test it :
I am new to Javascript, and I wouldn't have gone for this solution unless this was the method our professor told us to use. I'm really frustrated here, and I'm just trying to get the hang of this.
Splitting a string turns it into an array. Treating an array as a string is equivalent to calling yourArray.join(','). Since you don't want to add commas, don't just treat the array as a string.
If you want to put HTML line breaks in, then you need to do so explicitly.
var array_of_lines = document.getElementById("myTextarea").value.split("\n");
var string_of_html = array_of_lines.join("<br>");
document.getElementById("text").innerHTML = string_of_html;
If you don't want HTML special characters to be treated as having special meaning, then convert each line to a text node and append it instead.
var array_of_lines = document.getElementById("myTextarea").value.split("\n");
document.getElementById("text").innerHTML = "";
while(var text = array_of_lines.unshift()) {
document.getElementById("text").appendChild(
document.createTextNode(text)
);
document.getElementById("text").appendChild(
document.createElement("br")
);
}

How can I ltrim and rtrim select characters in Javascript?

So I am trying to figure out how I can remove a select set of characters on the end of a string. I've tried some general 'solutions' like str.replace or creating a rtrim, but I kept seeing some situation in which it wouldn't work.
Possible inputs might be:
\r\n some random text \r\n
\r\n some random text
some random text \r\n
some random text
Only the first and the third line should be affected by this function.
Basicly I'm looking for a rtrim function that takes as a parameter, the value/character set that should be trimmed.
I think it might be something way too obvious that I don't see, but at this point I feel like I could use some help.
You can use the following piece of code to do that for you:
var a = "\r\n some random text \r\n";
a = a.replace(new RegExp('\r\n$'), '');
Here, $ matches end of input.
You can refer to the regular expressions guide here to find out more about regex in JS.
EDIT:
If you really need a function for this:
var rTrimRegex = new RegExp('\r\n$');
var rTrim = function(input){
return input.replace(rTrimRegex, '');
}
And then use it inside your code maybe like:
var str = 'my name is foo\r\n\r\n';
str = rTrim(str);

JavaScript string replace() not working when replacing variable

I'm trying to create a JavaScript script for highlighting certain text on a page. Right now I'm having issues trying to replace text (from the body html) with other text. I want to replace all instances of each item in the array highlights with some other text.
The code that I'm using is:
var responseText = server.responseText;
var highlights = responseText.split("\n");
var text = document.body.innerHTML;
for (i in highlights) {
if (highlights[i].length > 1) {
var exp = new RegExp(highlights[i], "g");
console.log(exp);
console.log(highlights[i]);
text = text.replace(exp, "XXXXXXXXXXX");
}
}
document.body.innerHTML = text;
Currently, I am getting the correct value printouts for highlights[i] and I think I am for the regular expression exp; if highlights[i] is 'Remember', then the printout I'm getting for exp is '/Remember/g' (without the quotation marks) -- but it's not replacing the word 'Remember' on the page. 'And if I replace highlights[i] in the new RegExp() with simply the string "Remember" it works correctly. Any ideas on what's wrong?
EDIT:
I solved the problem! When creating the RegExp() I passed in highlights[i].trim() instead of just highlights[i] to get rid of whitespace at the beginning/end and it appears to be working now.
There is some problem with your multiline server.responseText .
I replaced the input with spaces instead of newlines, and all the replacements work fine :
http://jsfiddle.net/XTdgJ/1/

read characters and words in HTML text using javascript

consider that i am getting a HTML format string and
want to read the number of words & characters,
Consider, i am getting,
var HTML = '<p>BODY Article By Archie(Used By Story Tool)</p>';
now i want to get number of words and characters
above html will look like:
BODY Article By Archie(Used By Story Tool)
IMPORTANT
i want to avoid html tags while counting words or character
avoid keywords like ** ** etc..
Ex. words and character should be counted of : (for current example)
BODY Article By Archie(Used By Story Tool)
please help,
Thank You.
To give an example for adamantium's suggestion:
var e = document.createElement("span");
e.innerHTML = '<p>BODY Article By Archie(Used By Story Tool)</p>';
var text = e.textContent || e.innerText;
var characterCount = text.length;
var wordCount = text.split(/[\s\.\(\),]+/).length;
Update: Added other word-stop characters
Use a hidden HTML element that can render text like span or p
Assign the string to the innerHTML of the hidden element.
Count the characters using length property of innerText/textContent.
To read the word count you can
Split the innerText/textContent using empty space
Get the length of the returned array.
Algorithm:
Sweep through the entire html
Perform regex replaces
replace <.*> (regex for anyting tat stays withing <>)by nothing
replace /&nbsp/ by nothing
tip: can be done by replace function in javascript. hunt on w3schools.com
Now you have the clutter out!
then perform a simple word/character count

Categories

Resources