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 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.
@mplungjan He doesn't want to ignore the leading/trailing whitespace, though, he wants it in his output.
– CertainPerformance
Aug 30 at 6:54