Split string in JavaScript and detect line break Split string in JavaScript and detect line break javascript javascript

Split string in JavaScript and detect line break


Use the following:

var enteredText = document.getElementById("textArea").value;var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;alert('Number of breaks: ' + numberOfLineBreaks);

DEMO

Now what I did was to split the string first using linebreaks, and then split it again like you did before. Note: you can also use jQuery combined with regex for this:

var splitted = $('#textArea').val().split("\n");           // will split on line breaks

Hope that helps you out!


Split string in JavaScript

var array = str.match(/[^\r\n]+/g);

OR

var array = str.split(/\r?\n/);

Performance


In case you need to split a string from your JSON, the string has the \n special character replaced with \\n.

Split string by newline:

Result.split('\n');

Split string received in JSON, where special character \n was replaced with \\n during JSON.stringify(in javascript) or json.json_encode(in PHP). So, if you have your string in a AJAX response, it was processed for transportation. and if it is not decoded, it will sill have the \n replaced with \\n** and you need to use:

Result.split('\\n');

Note that the debugger tools from your browser might not show this aspect as you was expecting, but you can see that splitting by \\n resulted in 2 entries as I need in my case:enter image description here