0

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 ?

7
  • You don't need the g flag with split, it splits on every occurrence by default. Commented Apr 14, 2016 at 6:40
  • You can try "A//B/C".split(/\//).filter(Boolean); Commented Apr 14, 2016 at 6:42
  • "A//B/C".split(/\//) gives ["A", "", "B", "C"] @RobG Commented Apr 14, 2016 at 6:43
  • 1
    Why do you expect ["A/", "B", "C"]? Please explain why the first / shouldn't produce a split. Commented Apr 14, 2016 at 6:53
  • 1
    what should your regex match i case of "A/" ? Commented Apr 14, 2016 at 7:08

3 Answers 3

5

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/)
Sign up to request clarification or add additional context in comments.

2 Comments

\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.
yes it seems it works that way. since first forward slash is a word boundary itself just like what you've said :)
2

Try RegExp /\/(?=[A-Z]|$)/ to match / if followed by A-Z or end of input

"A//B/C".split(/\/(?=[A-Z]|$)/)

4 Comments

"A//B/C/".split(/\/(?=[A-Z]|$)/) gives ["A/", "B", "C", ""] but "A//B/C/".split(/\/\b/) gives ["A/", "B", "C/"]
@lintocheeran Yes. What is expected result? "A//B/C/" does not appear at nor is expected result of "A//B/C/" described at Question?
sorry i expecting pattern not static one
@lintocheeran "sorry i am expect pattern not static one" ? What do you mean by "pattern"? What is pattern? What do you mean by "not static one"?
0

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

2 Comments

"A//B/C/".split(/\/(?!\/)/); giving ["A/", "B", "C", ""] it's not match pattern like [A-Z]/
right, I asked the OP how to handle this case. If "A/" should result i ["A/"], then my answer is incorrect and the word boundary propose is the way to go. or similarly this would work: /\/(?=[^/])/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.