2

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"]
1
  • .match(/(\S+)\s+(\S+)\s+(.+)/).slice(1) Commented Apr 28, 2019 at 18:49

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

But I got only ["224", "Brandywine"] ?
This does not do what the OP wants. It will only give you the first two items
This also does not give desired result.
3

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));

1 Comment

Your code works but I just want to see if there is a shorter way to achieve it. Still many thanks.
1

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];

1 Comment

Your code gives me back : [ "224", "Brandywine", "randywine Court Fairfield CA 94533" ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.