这是一个很好的策略,可以将完整的单词添加到具有后续角色的数组中。
实施例。 这是一个惊人的句子。
Array(
[0] => This
[1] => is
[2] => an
[3] => amazing
[4] => sentence.
)
元素0 - 3会有一个后续空格,因为一个句点接替第四个元素。
我的想法是说... 嘿,我需要你通过间距字符来分割它们, 然后,一旦注入的数组元素的宽度达到X, 闯入新的界限。
拜托,gawd不要提供大量的代码。我更愿意写自己的,只要告诉我你会怎么做。
答案 0 :(得分:36)
只需使用split
:
var str = "This is an amazing sentence.";
var words = str.split(" ");
console.log(words);
//["This", "is", "an", "amazing", "sentence."]
如果你需要一个空间,你为什么不这样做呢? (之后使用循环)
var str = "This is an amazing sentence.";
var words = str.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
console.log(words);
//["This ", "is ", "an ", "amazing ", "sentence."]
哦,睡得好!
答案 1 :(得分:31)
与Ravi's answer类似,请使用match
,但在正则表达式中使用边界\b
来分割字边界:
'This is a test. This is only a test.'.match(/\b(\w+)\b/g)
产量
["This", "is", "a", "test", "This", "is", "only", "a", "test"]
或
'This is a test. This is only a test.'.match(/\b(\w+\W+)/g)
产量
["This ", "is ", "a ", "test. ", "This ", "is ", "only ", "a ", "test."]
答案 2 :(得分:13)
试试这个
var words = str.replace(/([ .,;]+)/g,'$1§sep§').split('§sep§');
这将
§sep§
[ .,;]+
答案 3 :(得分:6)
如果你需要空格和最简单的圆点。
"This is an amazing sentence.".match(/.*?[\.\s]+?/g);
结果将是
['This ','is ','an ','amazing ','sentence.']
答案 4 :(得分:1)
如果您想要包含空格并在O(N)中完成
,这是一个选项var str = "This is an amazing sentence.";
var words = [];
var buf = "";
for(var i = 0; i < str.length; i++) {
buf += str[i];
if(str[i] == " ") {
words.push(buf);
buf = "";
}
}
if(buf.length > 0) {
words.push(buf);
}
答案 5 :(得分:0)
这可以通过lodash _.words
完成:
var str = 'This is an amazing sentence.';
console.log(_.words(str, /[^, ]+/g));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 6 :(得分:0)
let str = ' This is an amazing sentence. ',
words = str.split(' ').filter(w => w !== '');
console.log(words);
答案 7 :(得分:0)
可以用 split
函数完成:
"This is an amazing sentence.".split(' ')