0

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?

Community
  • 1
  • 1
Dexygen
  • 12,287
  • 13
  • 80
  • 147
  • because the entities are still there inside the in-memory string. you're just seeing the RENDERED version of those entities. try splitting on ` ` instead. That or run the string through an entity->raw decode cycle first. – Marc B May 12 '15 at 15:07
  • I am voting to close my own question (it wouldn't let me delete it) due to beercohol's answer which, though it solves my problem, also shows that it's a poor question that won't help others in the future. So if you come along this in the future and are tempted to downvote the question, vote to close it instead ;) – Dexygen May 12 '15 at 15:30

2 Answers2

1

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/

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
1

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.

beercohol
  • 2,577
  • 13
  • 26