linto cheeran
linto cheeran

Reputation: 1472

javascript split() using regEx

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 ?

Upvotes: 0

Views: 316

Answers (3)

JF-Mechs
JF-Mechs

Reputation: 1081

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/)

Upvotes: 6

Anton Harald
Anton Harald

Reputation: 5934

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

Upvotes: 0

guest271314
guest271314

Reputation: 1

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

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

Upvotes: 2

Related Questions