mwilson
mwilson

Reputation: 12910

Negative Lookbehind in firefox

I just learned the hard way that negative lookbehinds are not supported in firefox. Just deployed to production and all seemed fine. Once our firefox users started hitting it, they got nothing.

Is there a pollyfill or some alternative to this regex?

"Item 1, Item2^, Item2a, Item3".split(/(?<!\^),/)

I am trying to split a string into arrays on a commas but not on ^,

"Item 1, Item2^, Item2a, Item3"

Should end up as

[
"Item 1",
"Item2^, Item2a",
"Item3"
]

Upvotes: 2

Views: 352

Answers (2)

user557597
user557597

Reputation:

As said in the comments JS doesn't support lookbehinds in the old EmcaScript version.
The new version (6 I think does support it).

No matter, what you can do is a find all regex that matches what you need.

Find /\s*((?:(?!\s*(?:,|$))[^,\^])*(?:\^,?(?:(?!\s*(?:,|$))[^,\^])*)*)\s*,?\s*/g

Where the element is in capture group 1 every match.
Note this regex does whitespace trimming, otherwise it would be very small.

Readable regex

 \s* 
 (                             # (1 start)
      (?:
           (?! \s* (?:,|$) )
           [^,\^] 
      )*

      (?:
           \^,?
           (?:
                (?! \s* (?:,|$) )
                [^,\^] 
           )*
      )*
 )                             # (1 end)
 \s* 
 ,?
 \s* 

JS Demo

var arr = [];
var str = "Item 1, Item2^, Item2a, Item3  ,,, ii , kkk ";
var re = /\s*((?:(?!\s*(?:,|$))[^,\^])*(?:\^,?(?:(?!\s*(?:,|$))[^,\^])*)*)\s*,?\s*/g;

str.replace( re, function( m, grp1 ) {
     arr.push( grp1 );
    });

console.log( arr );

Upvotes: 2

georg
georg

Reputation: 214969

As an alternative, there's always good old "double replacement" for you:

r = "Item 1, Item2^, Item2a, Item3"
  .replace(/,/g, '~')
  .replace(/\^~/g, '^,')
  .split(/~ /g)
 
console.log(r)

Basically, /(?<! X) Y/ is "unrolled" into three steps:

  • replace Y => temp
  • replace X temp back to X Y
  • now temp is what you want

Upvotes: 2

Related Questions