Nishil S.B
Nishil S.B

Reputation: 69

How to split conditionally in Javascript?

I have a string like this

"Earth Continuity (4;1) due to;Electric safety devices(4;2) due to;Electric safety devices(4;2) Top Final Limit Switch"

and I need to split this string and the output should look like Bello

[Earth Continuity (4;1) due to,Electric safety devices(4;2) due to,
Electric safety devices(4;2) Top Final Limit Switch]

here the delimiter is ; but if a digit comes before and after the delimiter for example (4;5), I need to skip the splitting hence I can't split using ; instead I need Regexp to do this.

can anyone help me out to solve this problem?

Upvotes: 0

Views: 70

Answers (1)

Wais Kamal
Wais Kamal

Reputation: 6180

Pass a regex rather than a string to the split function:

var str = "Earth Continuity (4;1) due to;Electric safety devices(4;2) due to;Electric safety devices(4;2) Top Final Limit Switch";
var splitStr = str.split(/(?<!\d);(?!\d)/)

console.log(splitStr);

Explanation:

  • (?<!) signifies a negative lookbehind
  • \d in (?<!\d) represents a number (0-9)
  • ; literally matches a semicolon ;
  • (?!) is a negative lookahead

Upvotes: 3

Related Questions