我有这个字符串
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 on the first white space occurrence,但这仅适用于第一个空格。
答案 0 :(得分:5)
使用拆分和联接进行解构
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])
答案 1 :(得分:3)
来源:Split a string only the at the first n occurrences of a delimiter
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);
答案 2 :(得分:1)
您可以先在所有空间上分割,然后取两个值并合并其余的值。
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)
答案 3 :(得分:0)
以这种方式使用正则表达式^(\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]);
答案 4 :(得分:0)
您可以通过编写一些代码来实现:
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' ]
答案 5 :(得分:0)
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);