Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Split string by first 2 white spaces

Tags:

javascript

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"]
like image 436
tomen Avatar asked Jun 18 '26 10:06

tomen


2 Answers

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()
like image 54
JayJamesJay Avatar answered Jun 19 '26 23:06

JayJamesJay


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));
like image 21
George Avatar answered Jun 20 '26 00:06

George