JavaScript 用空格分割字符串

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

JavaScript split String with white space

javascriptarrayssplit

提问by Jose

I would like to split a String but I would like to keep white space like:

我想拆分一个字符串,但我想保留空白,例如:

var str = "my car is red";

var stringArray [];

stringArray [0] = "my";
stringArray [1] = " ";
stringArray [2] = "car";
stringArray [3] = " ";
stringArray [4] = "is";
stringArray [5] = " ";
stringArray [6] = "red";

How I can proceed to do that?

我如何才能继续这样做?

Thanks !

谢谢 !

采纳答案by somethinghere

You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.

您可以在空白处拆分字符串,然后重新添加它,因为您知道它位于每个条目之间。

var string = "text to split";
    string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
    stringArray.push(string[i]);
    if(i != string.length-1){
        stringArray.push(" ");
    }
}

Update: Removed trailing space.

更新:删除了尾随空格。

回答by chridam

Using regex:

使用正则表达式:

var str   = "my car is red";
var stringArray = str.split(/(\s+)/);

console.log(stringArray); // ["my", " ", "car", " ", "is", " ", "red"] 

\smatches any character that is a whitespace, adding the plus makes it greedy, matching a group starting with characters and ending with whitespace, and the next group starts when there is a character after the whitespace etc.

\s匹配任何作为空格的字符,添加加号使其贪婪,匹配以字符开头并以空格结尾的组,当空格后面有一个字符时,下一组开始等。

回答by Dmitriy Yusupov

For split string by space like in Python lang, can be used:

对于像 Python lang 那样按空格分割字符串,可以使用:

   var w = "hello    my brothers    ;";
   w.split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );

output:

输出:

   ["hello", "my", "brothers", ";"]

or similar:

或类似:

   w.split(/(\s+)/).filter( e => e.trim().length > 0)

(output some)

(输出一些)

回答by Rhumborl

You can just split on the word boundary using \b. See MDN

您可以使用\b. 见MDN

"\b: Matches a zero-width word boundary, such as between a letter and a space."

“\b:匹配零宽度的单词边界,例如字母和空格之间。”

You should also make sure it is followed by whitespace \s. so that strings like "My car isn't red"still work:

您还应该确保其后跟有空格\s。所以像这样的字符串"My car isn't red"仍然有效:

var stringArray = str.split(/\b(\s)/);

The initial \bis required to take multiple spaces into account, e.g. my car is red

\b需要首字母来考虑多个空格,例如my car is red

EDIT: Added grouping

编辑:添加分组

回答by Lightness Races in Orbit

Although this is not supported by all browsers, if you use capturing parentheses inside your regular expression then the captured input is spliced into the result.

尽管并非所有浏览器都支持这种方式,但如果您在正则表达式中使用捕获括号,则捕获的输入将拼接到结果中。

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. [reference)

如果separator是一个包含捕获括号的正则表达式,那么每次匹配separator时,将捕获括号的结果(包括任何未定义的结果)拼接到输出数组中。[参考]

So:

所以:

var stringArray = str.split(/(\s+)/);
                             ^   ^
//

Output:

输出:

["my", " ", "car", " ", "is", " ", "red"]

This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls.

这会折叠原始输入中的连续空格,但除此之外我想不出任何陷阱。

回答by Esger

str.split(' ').join('§ §').split('§');