Socrates Socrates - 1 year ago 46
Javascript Question

Regex match digits between two strings not working in JS

I have a regex which is working fine in regex101 but not in javascript/jquery, I think because of the

expression. If I omit this part, it works, but replaces the preceding string as well. I want to replace only the digits in the URL, or in other words all digits between "foo/" and "/bar"

My code:

<a id="link" href="">Some anchor text</a>

$("button").click(function() {
$('#link').attr('href', function(index, myhref) {
return myhref.replace(/(?<=foo\/)(\d+)(?=\/bar)/,'newnumber');

How do I have to modify my regex so that it replaces the digits?

Answer Source

JavaScript doesn't support positive or negative lookbehind. But, you might want to try to capture its group and use them as you're replacing the string.


var str = '';
var myvar = 'newnumber';
var newStr = str.replace(/(foo\/)(\d+)(\/bar)/i, '$1' + myvar + '$3');
// Returns ""
  • (foo\/) is the first group, matching foo/
  • (\d+) is the second group, matching any digits number for one or more.
  • (\/bar) is the third group, matching /bar
  • '$1'+ myvar +'$3' returns a concat of first group + myvar + third group