[英]Quick javascript split question
Just a quick question regarding the split function 关于拆分功能的一个简单问题
How can I split my string at every 2nd space? 如何在每个第二个空间分割我的弦?
myArray = 'This is a sample sentence that I am using'
myArray = myString.split(" ");
I would like to create a array like this 我想创建一个像这样的数组
This is a < 2 spaces sample sentence that < 2 spaces that I am < 2 spaces
and if the last word is not a space how would I handle this...? 如果最后一个字不是空格,我该如何处理...?
any help would be appreciated 任何帮助,将不胜感激
myString = 'This is a sample sentence that I am using';
myArray = myString.match(/[^ ]+( +[^ ]+){0,2}/g);
alert(myArray);
Not a beautiful solution. 不是一个美丽的解决方 Assumes the
\\1
character isn't used. 假设未使用
\\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);
Split it every space, and then concatenate every other element: 将它拆分到每个空间,然后连接每个其他元素:
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;
}
Havent tested the code, but should work 没有测试代码,但应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.