Invalid regular expression error

戏子无情 提交于 2020-01-21 12:08:43

问题



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]);

回答1:


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.




回答2:


The syntax is messing up your code.

var urlRE = url.match(/category=([a-z-]+)/);
alert(urlRE[1]);



回答3:


If you want to parse URL parameters, you can use the getParameterByName() function from this site:

  • http://james.padolsey.com/javascript/bujs-1-getparameterbyname/

In any case, as already mentioned, regular expressions in JavaScript are not plain strings:

  • https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions



回答4:


  var url = "property_id=516&category=featured-properties",

  urlRE = url.match(/(category=)([a-z-]+)/i); //don't forget i if you want to match also uppercase letters in category "property_id=516&category=Featured-Properties"
  //urlRE = url.match(/(?<=(category=))[a-z-]+/i); //this is a mess

  alert(urlRE[2]); 


来源:https://stackoverflow.com/questions/5952936/invalid-regular-expression-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!