Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid regular expression error


I'm trying to retrieve the category part this string "property_id=516&category=featured-properties", so the result should be "featured-properties", and I came up with a regular expression and tested it on this website http://gskinner.com/RegExr/, and it worked as expected, but when I added the regular expression to my javascript code, I had a "Invalid regular expression" error, can anyone tell me what is messing up this code?

Thanks!

var url = "property_id=516&category=featured-properties"
var urlRE = url.match('(?<=(category=))[a-z-]+');
alert(urlRE[0]);
like image 208
KarimMesallam Avatar asked Dec 22 '22 14:12

KarimMesallam


2 Answers

Positive lookbehinds (your ?<=) are not supported in JavaScript environments that do not comply with ECMAScript 2018 standard, which is causing your RegEx to fail.

You can mimic them in a whole bunch of different ways, but this might be a simpler RegEx to get the job done for you:

var url = "property_id=516&category=featured-properties"
var urlRE = url.match(/category=([^&]+)/);
// urlRE => ["category=featured-properties","featured-properties"]
// urlRE[1] => "featured-properties"

That's a super-simple example, but searching StackOverflow for a RegEx pattern to parse URL parameters will turn up more robust examples if you need them.

like image 139
ajm Avatar answered Dec 25 '22 23:12

ajm


The syntax is messing up your code.

var urlRE = url.match(/category=([a-z-]+)/);
alert(urlRE[1]);
like image 26
DanielB Avatar answered Dec 25 '22 23:12

DanielB