Exploring
Exploring

Reputation: 3389

how to split on specific string in nodejs?

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.

Upvotes: 0

Views: 181

Answers (1)

tmarwen
tmarwen

Reputation: 16364

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 pattern would be as follows:

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

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

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

Upvotes: 1

Related Questions