Socrates Socrates - 6 months ago 15
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="http://www.domain.com/foo/1234/bar/">Some anchor text</a>
<button>Click</button>

$("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

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.

E.g

var str = 'http://www.domain.com/foo/1234/bar/';
var myvar = 'newnumber';
var newStr = str.replace(/(foo\/)(\d+)(\/bar)/i, '$1' + myvar + '$3');
// Returns "http://www.domain.com/foo/newnumber/bar/"
  • (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