关于拆分功能的快速问题
如何在第二个空格分割我的字符串?
myArray = 'This is a sample sentence that I am using'
myArray = myString.split(" ");
我想创建一个像这样的数组
This is a < 2 spaces sample sentence that < 2 spaces that I am < 2 spaces
如果最后一个单词不是空格,我该如何处理...?
任何帮助将不胜感激
答案 0 :(得分:2)
myString = 'This is a sample sentence that I am using';
myArray = myString.match(/[^ ]+( +[^ ]+){0,2}/g);
alert(myArray);
答案 1 :(得分:1)
不是一个漂亮的解决方案。假设未使用\1
字符。
array = 'This is a sample sentence that I am using';
array = array.replace(/(\S+\s+\S+\s+\S+)\s+/g, "$1\1").split("\1");
// If you want multiple whitespaces not merging together
// array = array.replace(/(\S*\s\S*\s\S*)\s/g, "$1\1").split("\1");
// If you only want to match the space character (0x20)
// array = array.replace(/([^ ]+ +[^ ]+ +[^ ]+) +/g, "$1\1").split("\1");
alert(array);
答案 2 :(得分:1)
将每个空格拆分,然后连接每个其他元素:
function splitOnEvery(str, splt, count){
var arr = str.split(splt);
var ret = [];
for(var i=0; i<arr.length; i+=count){
var tmp = "";
for(var j=i; j<i+count; j++){
tmp += arr[j];
}
ret.push(tmp);
}
return ret;
}
没有测试过代码,但应该可以使用