string 在Javascript中按空格和新行拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17271324/
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-09-09 01:59:57  来源:igfitidea点击:

split string by space and new line in Javascript

javascriptstringsplit

提问by lol2x

I am trying to split values in string, for example I have a string:

我正在尝试拆分字符串中的值,例如我有一个字符串:

var example = "X Y\nX1 Y1\nX2 Y2"

and I want to separate it by spaces and \nso I want to get something like that:

我想用空格分隔它,\n所以我想得到类似的东西:

var 1 = X
var 2 = Y
var 3 = X1
var 4 = Y1

And is it possible to check that after the value XI have an Y? I mean Xand Yare Lat and Lon so I need both values.

是否可以在值之后检查X我有一个Y?我的意思是XY是纬度和经度,所以我需要两个值。

回答by JJJ

You can replace newlines with spaces and then split by space (or vice versa).

您可以用空格替换换行符,然后按空格拆分(反之亦然)。

example.replace( /\n/g, " " ).split( " " )

Demo: http://jsfiddle.net/fzYe7/

演示:http: //jsfiddle.net/fzYe7/

If you need to validate the string first, it might be easier to first split by newline, loop through the result and validate each string with a regex that splits the string at the same time:

如果您需要先验证字符串,首先按换行符拆分,循环遍历结果并使用同时拆分字符串的正则表达式验证每个字符串可能更容易:

var example = "X Y\nX1 Y1\nX2 Y2";
var coordinates = example.split( "\n" );
var results = [];

for( var i = 0; i < coordinates.length; ++i ) {
    var check = coordinates[ i ].match( /(X.*) (Y.*)/ ); 

    if( !check ) {
        throw new Error( "Invalid coordinates: " + coordinates[ i ] );
    }

    results.push( check[ 1 ] );
    results.push( check[ 2 ] );    
}

Demo: http://jsfiddle.net/fzYe7/1/

演示:http: //jsfiddle.net/fzYe7/1/

回答by gmaliar

var string = "x y\nx1 y1\nx2 y2";
var array = string.match(/[^\s]+/g);

console.log(array); 

jsfiddle: http://jsfiddle.net/fnPR8/

jsfiddle:http: //jsfiddle.net/fnPR8/

it will break your string into an array of words then you'd have to iterate over it ...

它会将您的字符串分解为一组单词,然后您必须对其进行迭代......

回答by Kevin Bowersox

Use a regex to split the String literal by all whitespace.

使用正则表达式按所有空格拆分字符串文字。

var example = "X Y \nX1 Y1 \nX2 Y2";
var tokens = example.split(/\s+/g);

console.log(tokens.length);
for(var x = 0; x < tokens.length; x++){
   console.log(tokens[x]);
}

Working Examplehttp://jsfiddle.net/GJ4bw/

工作示例http://jsfiddle.net/GJ4bw/

回答by dev2d

you can split it by new char first and store it in an array and then you can split it by spcae.

您可以先用新字符拆分它并将其存储在一个数组中,然后您可以用 spcae 拆分它。

following may give a referance Link

下面可以给个参考链接