152

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)
j08691
  • 204,283
  • 31
  • 260
  • 272
oknoorap
  • 1,923
  • 2
  • 14
  • 20

13 Answers13

213

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"]
Dominic Fox
  • 118
  • 11
Adi Azarya
  • 4,015
  • 3
  • 18
  • 26
102

Try initializing the ks variable inside your submit function.

  (function($){
     $(document).ready(function(){
        $('#data').submit(function(e){
           var ks = $('#keywords').val().split("\n");
           e.preventDefault();
           alert(ks[0]);
           $.each(ks, function(k){
              alert(k);
           });
        });
     });
  })(jQuery);
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
  • 3
    alert(k) only alerts the sequence number, not the value. You should alert(ks[k]) – HBlackorby Jun 05 '15 at 19:40
  • 2
    @hblackorby Your comment, although relevant, is somewhat of a mute point as OP's primary issue here was scope and initialization of his variable "ks" – John Hartsock Jun 08 '15 at 15:19
65

It should be

yadayada.val.split(/\n/)

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

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 5
    `"\n"` and `/\n/` are two ENTIRELY different things in JS. `"` = string, `/` = regex. – Marc B May 29 '14 at 15:53
  • 27
    Yes, but what is the effective difference? Don't `"\n"` and `/\n/` match the same things? – Scott Stafford May 30 '14 at 18:19
  • 25
    Both "\n" and /\n/ will work about the same, but depending on the source you are splitting, something like val.split(/[\r\n]+/) may be better. If your source has "\r\n" line-breaks then splitting on "\n" leaves the "\r" on the end which can cause problems. – xtempore May 20 '16 at 00:47
  • works like a charm. I'm using react so I cant use jquery. – Brandon Apr 08 '21 at 15:03
  • You might also want to [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) the resulted strings to get rid of newline parts, such as `\r` – ivanjermakov Feb 22 '22 at 23:37
37

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

Community
  • 1
  • 1
Ahsan
  • 3,845
  • 2
  • 36
  • 36
  • 30
    or, more specifically, `/\r?\n/` ... I think using `|` (or) would interleave empty results for CRLF line endings. – Dusty Oct 05 '16 at 16:39
  • You're not going to see CR-only (`\r`) [line breaks](https://en.wikipedia.org/wiki/Newline#Representation) anywhere on the modern web. The last place where they were widely used was in [ancient Mac OS versions](https://en.wikipedia.org/wiki/Classic_Mac_OS) from nearly 20 years ago. – Ilmari Karonen Sep 25 '19 at 21:36
14

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.

Jack Ting
  • 552
  • 4
  • 6
11

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:

var examples = ["Foo\r\nBar", "Foo\r\n\r\nBar", "Foo\n\r\n\rBar", "Foo\nBar\nFooBar"];

examples.forEach(function(example) {
  output(`Example "${example}":`);
  output(`Split using "\n": "${example.split("\n")}"`);
  output(`Split using /\r?\n/: "${example.split(/\r?\n/)}"`);
  output(`Split using /\r\n|\n|\r/: "${example.split(/\r\n|\n|\r/)}"`);
  output(`Current method: ${example.replace(/\r/g, "").split("\n")}`);
  output("________");
});

function output(txt) {
  console.log(txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r"));
}
nick zoum
  • 7,216
  • 7
  • 36
  • 80
3
  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

amit_g
  • 30,880
  • 8
  • 61
  • 118
1

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]);  
check123
  • 1,989
  • 2
  • 22
  • 28
0

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);
steveyang
  • 9,178
  • 8
  • 54
  • 80
0

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

ValeriiVasin
  • 8,628
  • 11
  • 58
  • 78
-1

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

<textarea id="keywords">Hello
World</textarea>
<input id="data" type="button" value="submit">
ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
  • 1
    this approach is well covered by the existing answers – KyleMit Sep 24 '19 at 04:04
  • @KyleMit yeah, I go through those answers, most probable answers are similar due to basic concept of javascript, but I focus or concern with the line of code that is why I posted this answer... – ankitkanojia Sep 24 '19 at 04:14
-1

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);
-1

In React Native, I have accomplish splitting by new line character via double back slashes, first one is as an escape character:

data = str.split("\\n");
  • Close! For it to work properly for me, I needed to remove the first escape character. str.split("\n") – Holly E Dec 07 '21 at 19:41