简体   繁体   English

Javascript - 按前 2 个空格拆分字符串

[英]Javascript - Split string by first 2 white spaces

I have a string, which contains multiple white spaces.我有一个字符串,其中包含多个空格。 I want to split it by only first 2 white spaces.我只想将它拆分为前 2 个空格。

224 Brandywine Court Fairfield, CA 94533

output输出

["224", "Brandywine", "Court Fairfield, CA 94533"]

 const str ="224 Brandywine Court Fairfield, CA 94533"; const arr = str.split(" "); const array = arr.slice(0, 2).concat(arr.slice(2).join(" ")); console.log(array);

You can do it with split and slice functions.您可以使用 split 和 slice 函数来做到这一点。

Here is how I might do it.这是我可能会这样做的方法。

 const s = "224 Brandywine Court Fairfield, CA 94533"; function splitFirst(s, by, n = 1){ const splat = s.split(by); const first = splat.slice(0,n); const last = splat.slice(n).join(by); if(last) return [...first, last]; return first; } console.log(splitFirst(s, " ", 2));

If you only care about the space character (and not tabs or other whitespace characters) and only care about everything before the second space and everything after the second space, you can do it:如果您只关心空格字符(而不是制表符或其他空格字符)并且只关心第二个空格之前的所有内容和第二个空格之后的所有内容,则可以这样做:

let str = `224 Brandywine Court Fairfield, CA 94533`;
let firstWords = str.split(' ', 2);
let otherWords = str.substring(str.indexOf(' ', str.indexOf(' ') + 1));
let result = [...firstWords, otherWords];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM