i want to split "A//B/C" string using javascript split() function
"A//B/C".split(/\//g)
but it's output is ["A", "", "B", "C"]but my expected output is
["A/", "B", "C"]
how i do this using javascript ?
I updated @Tushar answer and tried this an it works out for me..added \b to match just the forward slashes followed by a word boundary e.g., [a-z] and [0-9]
"A//B/C".split(/\/\b/)
\b matches a word boundary, it seems that / by itself is a boundary, but / followed by / is not a boundary since the first / isn't a word character. Interesting.Try RegExp /\/(?=[A-Z]|$)/ to match / if followed by A-Z or end of input
"A//B/C".split(/\/(?=[A-Z]|$)/)
"A//B/C/" does not appear at nor is expected result of "A//B/C/" described at Question?You need to split the string at a position, where the current character is "/" and the following character is not "/". However, the second (negative) condition should not be consumed by the regex. In other words: It shouldn't be regarded as delimeter. For this you can use a so called "look ahead". There is a positive "look ahead" and a negative one. Here we need a negative one, since we want to express "not followed by". The syntax is: (?!<string>), whereas is what shouldn't 'follow'.
So there you go: /\/(?!\/)/
applied to your example:
"A//B/C".split(/\/(?!\/)/); // ["A/", "B", "C"]
gflag with split, it splits on every occurrence by default."A//B/C".split(/\//).filter(Boolean);["A/", "B", "C"]? Please explain why the first/shouldn't produce a split.