简体   繁体   中英

Javascript - Regular Expression with string template followed by 4 digits number?

Good day. I wanna detect the url string in the <a> tag

<a href="http://virtualweb.test/en/?post_type=tribe_events&p=3642">Link</a>

whether it matchs the pattern : ?post_type=tribe_events&p=#### (#### = 4 digits number)

I'm writing some Jquery code to detect the expression but the console is throwing the error :

Invalid regular expression: /^(?)post_type=tribe_events&p=^(d{4})/: Invalid group

var str = $(a).attr("href");
var regexEx  = /^(?)post_type=tribe_events&p=^(d{4})/;
  var ok = regexEx.exec(str);
  console.log(ok);

I'm not good at the regex so I'd be aprreciated if there's any help.

There are couple of issues in your regex.

  • You need to remove ^ from your regex which denotes start of string and in your case your string doesn't actually start from a ? and is in middle of the string.
  • You need to escape ? as it has special meaning in regex which is zero or one occurrence of a character.
  • You need to remove second ^ after p= which isn't needed
  • You need to write \\d and not just d for representing a number.
  • Also you don't need to group ? and \\d{4} unless you really need them.

You corrected regex becomes,

\?post_type=tribe_events&p=\d{4}

Demo

如果测试真的是你想要的,我想正确的语法是:

/^\?post_type=tribe_events&p=\d{4}/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM