[jquery] Javascript how to split newline

I'm using jquery, and I have a textarea. When I submit by my button I will alert each text separated by newline. How to split my text when there is a newline?

  var ks = $('#keywords').val().split("\n");
  (function($){
     $(document).ready(function(){
        $('#data').submit(function(e){
           e.preventDefault();
           alert(ks[0]);
           $.each(ks, function(k){
              alert(k);
           });
        });
     });
  })(jQuery);

example input :

Hello
There

Result I want is :

alert(Hello); and
alert(There)

This question is related to jquery split

The answer is


  1. Move the var ks = $('#keywords').val().split("\n"); inside the event handler
  2. Use alert(ks[k]) instead of alert(k)

  (function($){
     $(document).ready(function(){
        $('#data').submit(function(e){
           e.preventDefault();
           var ks = $('#keywords').val().split("\n");
           alert(ks[0]);
           $.each(ks, function(k){
              alert(ks[k]);
           });
        });
     });
  })(jQuery);

Demo


It should be

yadayada.val.split(/\n/)

you're passing in a literal string to the split command, not a regex.


Since you are using textarea, you may find \n or \r (or \r\n) for line breaks. So, the following is suggested:

$('#keywords').val().split(/\r|\n/)

ref: check whether string contains a line break


_x000D_
_x000D_
(function($) {_x000D_
  $(document).ready(function() {_x000D_
    $('#data').click(function(e) {_x000D_
      e.preventDefault();_x000D_
      $.each($("#keywords").val().split("\n"), function(e, element) {_x000D_
        alert(element);_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
})(jQuery);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<textarea id="keywords">Hello_x000D_
World</textarea>_x000D_
<input id="data" type="button" value="submit">
_x000D_
_x000D_
_x000D_


The simplest and safest way to split a string using new lines, regardless of format (CRLF, LFCR or LF), is to remove all carriage return characters and then split on the new line characters. "text".replace(/\r/g, "").split(/\n/);

This ensures that when you have continuous new lines (i.e. \r\n\r\n, \n\r\n\r, or \n\n) the result will always be the same.

In your case the code would look like:

(function ($) {
    $(document).ready(function () {
        $('#data').submit(function (e) {
            var ks = $('#keywords').val().replace(/\r/g, "").split(/\n/);
            e.preventDefault();
            alert(ks[0]);
            $.each(ks, function (k) {
                alert(k);
            });
        });
    });
})(jQuery);

Here are some examples that display the importance of this method:

_x000D_
_x000D_
var examples = ["Foo\r\nBar", "Foo\r\n\r\nBar", "Foo\n\r\n\rBar", "Foo\nBar\nFooBar"];_x000D_
_x000D_
examples.forEach(function(example) {_x000D_
  output(`Example "${example}":`);_x000D_
  output(`Split using "\n": "${example.split("\n")}"`);_x000D_
  output(`Split using /\r?\n/: "${example.split(/\r?\n/)}"`);_x000D_
  output(`Split using /\r\n|\n|\r/: "${example.split(/\r\n|\n|\r/)}"`);_x000D_
  output(`Current method: ${example.replace(/\r/g, "").split("\n")}`);_x000D_
  output("________");_x000D_
});_x000D_
_x000D_
function output(txt) {_x000D_
  console.log(txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r"));_x000D_
}
_x000D_
_x000D_
_x000D_


you don't need to pass any regular expression there. this works just fine..

 (function($) {
      $(document).ready(function() {
        $('#data').click(function(e) {
          e.preventDefault();
          $.each($("#keywords").val().split("\n"), function(e, element) {
            alert(element);
          });
        });
      });
    })(jQuery);

Good'ol javascript:

 var m = "Hello World";  
 var k = m.split(' ');  // I have used space, you can use any thing.
 for(i=0;i<k.length;i++)  
    alert(k[i]);  

You should parse newlines regardless of the platform (operation system) This split is universal with regular expressions. You may consider using this:

var ks = $('#keywords').val().split(/\r?\n/);

E.g.

"a\nb\r\nc\r\nlala".split(/\r?\n/) // ["a", "b", "c", "lala"]

Just

var ks = $('#keywords').val().split(/\r\n|\n|\r/);

will work perfectly.

Be sure \r\n is placed at the leading of the RegExp string, cause it will be tried first.


The problem is that when you initialize ks, the value hasn't been set.

You need to fetch the value when user submits the form. So you need to initialize the ks inside the callback function

(function($){
   $(document).ready(function(){
      $('#data').submit(function(e){
      //Here it will fetch the value of #keywords
         var ks = $('#keywords').val().split("\n");
         ...
      });
   });
})(jQuery);

Here is example with console.log instead of alert(). It is more convenient :)

var parse = function(){
  var str = $('textarea').val();
  var results = str.split("\n");
  $.each(results, function(index, element){
    console.log(element);
  });
};

$(function(){
  $('button').on('click', parse);
});

You can try it here