[英]Split string for first two white spaces
我有这串
var str = "394987011016097814 1d the quick brown fox jumped over the lazy dog";
..而我正试图让它成为这个数组
[
"394987011016097814",
"1d",
"the quick brown fox jumped over the lazy fox",
]
我已经在第一个空格出现时看到了这个答案Split string,但这仅用于第一个空格。
使用拆分和联接进行解构
var str = "394987011016097814 1d the quick brown fox jumped over the lazy fox"; var [str1, str2, ...str3] = str.split(' '); str3 = str3.join(' '); console.log([str1, str2, str3])
var string = 'Split this, but not this', arr = string.split(' '), result = arr.splice(0,2); result.push(arr.join(' ')); // result is ["Split", "this,", "but not this"] alert(result);
您可以先在所有空间上分割,然后取两个值并合并其余的值。
var str = "394987011016097814 1d the quick brown fox jumped over the lazy fox"; let op = str.split(/[ ]+/g) let final = [...op.splice(0,2), op.join(' ')] console.log(final)
这样使用正则表达式^(\\d+)\\s(\\S+)\\s(.*)
var re = new RegExp(/^(\d+)\s(\S+)\s(.*)/, 'gi');
re.exec('394987011016097814 1d the quick brown fox jumped over the lazy fox');
var re = new RegExp(/^(\\d+)\\s(\\S+)\\s(.*)/, 'g'); var [, g1, g2, g3] = re.exec('394987011016097814 1d the quick brown fox jumped over the lazy fox'); console.log([g1, g2, g3]);
您可以通过编写一些代码来实现:
const str = "394987011016097814 1d the quick brown fox jumped over the lazy fox";
const splittedString = str.split(' ');
let resultArray = [];
let concatenedString = '';
for (let i = 0; i < splittedString.length; i++) {
const element = splittedString[i];
if (i === 0 || i === 1) {
resultArray.push(element);
} else {
concatenedString += element + ' ';
}
}
resultArray.push(concatenedString.substring(0, concatenedString.length - 1));
console.log(resultArray);
// output is:
// [ '394987011016097814',
// '1d',
// 'the quick brown fox jumped over the lazy fox' ]
let str = "394987011016097814 1d the quick brown fox jumped over the lazy fox"; let arr = []; str = str.split(' '); arr.push(str.shift()); arr.push(str.shift()); arr.push(str.join(' ')); console.log(arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.