Home > Software design >  how to split on specific string in nodejs?
how to split on specific string in nodejs?

Time:03-17

I want to split string for ">" but not when >> in JavaScript.

But once I am doing a split const words = str.split('>'); it is splitting >> as well.

Currently, after the split I look for "> >" and then substitute them with ">>".

How to implement it properly.

CodePudding user response:

You can use a regular expression leveraging:

  • Negative lookbehind (?>!) causing a group to not be considered when the pattern matches before the main expression
  • Negative lookahead (?!) causing a group to not be considered when the pattern matches after the main expression

The resulting patter would be as follows:

/(?<!>)>(?!>)/

Using the patter to tokenize an input would lead the desired results:

"here>>I>am".split(/(?<!>)>(?!>)/) // => [ 'here>>I', 'am' ]
  • Related