如何将一个字符串中每个单词和其后面的字符一起存入数组中的一个好策略是什么。
例如:
这是一个惊人的句子。
Array(
[0] => This
[1] => is
[2] => an
[3] => amazing
[4] => sentence.
)
元素0-3会有一个空格跟随,因为句点在第4个元素之后。
我需要您通过间隔字符将它们拆分, 然后一旦注入了数组元素的元素宽度达到X, 就换行。
请不要给我太多代码。我更喜欢自己编写,告诉我您会如何做。
如何将一个字符串中每个单词和其后面的字符一起存入数组中的一个好策略是什么。
例如:
这是一个惊人的句子。
Array(
[0] => This
[1] => is
[2] => an
[3] => amazing
[4] => sentence.
)
元素0-3会有一个空格跟随,因为句点在第4个元素之后。
我需要您通过间隔字符将它们拆分, 然后一旦注入了数组元素的元素宽度达到X, 就换行。
请不要给我太多代码。我更喜欢自己编写,告诉我您会如何做。
与Ravi的答案类似,使用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."]
/(\p{L}+\P{L}+)/
这样的正则表达式在ES2018(或PCRE)中可能有效,但我不确定是否有任何真正的支持。参考:https://dev59.com/OHVC5IYBdhLWcg3w51lv#48902765 - Isaac只需使用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."]
哦,还有好好睡觉!
.join(' ');
。 - Dennis Martinez试试这个
var words = str.replace(/([ .,;]+)/g,'$1§sep§').split('§sep§');
这将
[ .,;]+
后插入标记 §sep§
"This is an amazing sentence.".match(/.*?[\.\s]+?/g);
结果将会是
['This ','is ','an ','amazing ','sentence.']
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);
}
input.match(/[\p{L}\p{N}\p{S}\p{M}]+/gu)
' \t a 件数 ,;-asd'.match(/[\p{L}\p{N}\p{S}\p{M}]+/gu)
['a', '件数', '', 'asd']
_.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>
split
函数来完成:"This is an amazing sentence.".split(' ')
更改为
var newstringreplaced = string.replace(/\s/gi, " ,");`。编辑:应该注意,如果您的原始字符串没有逗号“,”,则此方法才有用。我认为这个解决方案更安全:https://dev59.com/B2855IYBdhLWcg3wJQvT#4514241。 - Suvi Vignarajah