最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - Split string by first 2 white spaces - Stack Overflow

programmeradmin2浏览0评论

I have a string, which contains multiple white spaces. I want to split it by only first 2 white spaces.

224 Brandywine Court Fairfield, CA 94533

output

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

I have a string, which contains multiple white spaces. I want to split it by only first 2 white spaces.

224 Brandywine Court Fairfield, CA 94533

output

["224", "Brandywine", "Court Fairfield, CA 94533"]
Share asked Apr 28, 2019 at 18:15 tomentomen 5399 silver badges21 bronze badges 1
  • .match(/(\S+)\s+(\S+)\s+(.+)/).slice(1) – georg Commented Apr 28, 2019 at 18:49
Add a ment  | 

3 Answers 3

Reset to default 5

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.

  • Array​.prototype​.slice()
  • String​.prototype​.split()

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];
发布评论

评论列表(0)

  1. 暂无评论