Dexygen
Dexygen

Reputation: 12561

Cannot split textarea on newline created from html entities

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&#13;&#10;Jane,3&#13;&#10;John,4&#13;&#10;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?

Upvotes: 0

Views: 230

Answers (2)

beercohol
beercohol

Reputation: 2587

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.

Upvotes: 1

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

You don't use \n and \r, so you can splite &#13; or &#10;.

var rows = textAreaValue.replace(/(&#[13|10];)+/g, "\n").split("\n");

Demo: http://jsfiddle.net/rr1zvxko/

Upvotes: 1

Related Questions