How to split string by space only in middle of string using JS

Viewed 197

Normal split works like this:

var a = " a @b c "
console.log(a.split(" "))
["", "a", "b", "c", ""]

But my expected output is: [" a", "@b", "c "] it is possible? And how?

3 Answers

One option is to use a regular expression and require word boundaries before and after the space:

var a = " a b c "
console.log(a.split(/\b \b/));

If non-word characters are allowed as well, you can use match instead - either match spaces at the beginning of the string, followed by non-spaces, or match non-spaces followed by spaces and the end of the string, or match non-spaces without restriction:

const a = " foo @bar c "
console.log(
  a.match(/^ *\S+|\S+ *$|\S+/g)
);

Lookbehind is another option, but it's not supported enough to be reliable in production code yet.

How about

a.split(/(?!^) (?!$)/)

If there may be more than one space and lookbehinds are supported then

a.split(/(?<!^ *) +(?! *$)/)

You can trim the string before the split, for example:

var a = " a b c ";
a = a.trim();
console.log(a.split(" "));

update

i was wrong to read the expected output, the result of my suggested code it's:

["a", "b", "c"] and not [" a", "b", "c "]

Related