Javascript how to split newline

oknoorap picture oknoorap · Nov 14, 2011 · Viewed 235.4k times · Source

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)

Answer

Adi Azarya picture Adi Azarya · Aug 16, 2017

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"]