jQuery Javascript如何拆分换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8125709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:03:55  来源:igfitidea点击:

Javascript how to split newline

jquerysplit

提问by oknoorap

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?

我正在使用 jquery,并且我有一个 textarea。当我通过我的按钮提交时,我会提醒每个用换行符分隔的文本。有换行符时如何拆分我的文本?

  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)

采纳答案by John Hartsock

Try initializing the ksvariable inside your submit function.

尝试初始化ks提交函数中的变量。

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

回答by Adi Azarya

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

回答by Marc B

It should be

它应该是

yadayada.val.split(/\n/)

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

您将文字字符串传递给 split 命令,而不是正则表达式。

回答by Raptor

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

由于您正在使用textarea,您可能会发现 \n 或 \r(或 \r\n)用于换行。所以,建议如下:

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

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

ref: check whether string contains a line break

ref:检查字符串是否包含换行符

回答by Hyman Ting

Just

只是

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

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

will work perfectly.

将完美地工作。

Be sure \r\nis placed at the leading of the RegExpstring, cause it will be tried first.

确保\r\n放在RegExp字符串的前导,因为它将首先被尝试。

回答by amit_g

  1. Move the var ks = $('#keywords').val().split("\n");inside the event handler
  2. Use alert(ks[k])instead of alert(k)
  1. 移动var ks = $('#keywords').val().split("\n");事件处理程序内部
  2. 使用alert(ks[k])代替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

演示

回答by nick zoum

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 charactersand then split on the new line characters. "text".replace(/\r/g, "").split(/\n/);

无论格式如何(CRLF、LFCR 或 LF),使用换行符拆分字符串的最简单和最安全的方法是删除所有回车符然后在新行字符上拆分"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.

这可确保当您有连续的新行(即\r\n\r\n\n\r\n\r、 或\n\n)时,结果将始终相同。

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"));
}

回答by check123

Good'ol javascript:

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

回答by ValeriiVasin

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

这是使用console.log而不是的示例alert()。更方便:)

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

你可以在这里试试

回答by steveyang

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

问题是当您初始化时ksvalue尚未设置。

You need to fetch the valuewhen user submits the form. So you need to initialize the ksinside the callback function

需要在用户提交表单时获取该值。所以需要在回调函数里面初始化ks

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