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

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



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?


[" a", "@b", "c "]





@mplungjan He doesn't want to ignore the leading/trailing whitespace, though, he wants it in his output.
– CertainPerformance
Aug 30 at 6:54






@ mplungjan It is not duplicate of what you mentioned. Should be reopened.
– VicJordan
Aug 30 at 6:55






Apologies... Here is the link for reference anyway: stackoverflow.com/questions/14912502/…
– mplungjan
Aug 30 at 7:40




3 Answers
3



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:


match




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.





What about string var a = " foo @bar c ", its not working correctly.
– hiacliok
Aug 30 at 8:08





See edit - use .match instead
– CertainPerformance
Aug 30 at 9:13


.match



How about



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


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



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



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


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



Required, but never shown



Required, but never shown






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)