4

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?

hiacliok
  • 239
  • 3
  • 7

3 Answers3

7

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

How about

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

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

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

MikeM
  • 13,156
  • 2
  • 34
  • 47
-3

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

mpdev7
  • 33
  • 3