Parse A Textarea In Substrings Based On Line Breaks In Javascript
I have a text area that I need to parse. Each new line needs to be pulled out and an operation needs to be performed on it. After the operation is done the operation needs to be
Solution 1:
Line breaks within the value
of a textarea are represented by line break characters (\r\n
in most browsers, \n
in IE and Opera) rather than an HTML <br>
element, so you can get the individual lines by normalizing the line breaks to \n
and then calling the split()
method on the textarea's value. Here is a utility function that calls a function for every line of a textarea value:
functionactOnEachLine(textarea, func) {
var lines = textarea.value.replace(/\r\n/g, "\n").split("\n");
var newLines, i;
// Use the map() method of Array where available if (typeof lines.map != "undefined") {
newLines = lines.map(func);
} else {
newLines = [];
i = lines.length;
while (i--) {
newLines[i] = func(lines[i]);
}
}
textarea.value = newLines.join("\r\n");
}
var textarea = document.getElementById("your_textarea");
actOnEachLine(textarea, function(line) {
return"[START]" + line + "[END]";
});
Solution 2:
If user is using enter key to go to next line in your text-area you can write,
var textAreaString = textarea.value;
textAreaString = textAreaString.replace(/\n\r/g,"<br />");
textAreaString = textAreaString.replace(/\n/g,"<br />");
textarea.value = textAreaString;
Post a Comment for "Parse A Textarea In Substrings Based On Line Breaks In Javascript"