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?

3
  • 1
    @mplungjan He doesn't want to ignore the leading/trailing whitespace, though, he wants it in his output. Commented Aug 30, 2018 at 6:54
  • @ mplungjan It is not duplicate of what you mentioned. Should be reopened. Commented Aug 30, 2018 at 6:55
  • Apologies... Here is the link for reference anyway: stackoverflow.com/questions/14912502/… Commented Aug 30, 2018 at 7:40

3 Answers 3

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.

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

1 Comment

What about string var a = " foo @bar c ", its not working correctly.
1

How about

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

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

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

Comments

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

Comments

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.