Socrates
Socrates

Reputation: 189

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?

Upvotes: 0

Views: 573

Answers (4)

choz
choz

Reputation: 17858

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

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can use .match() with RegExp /\d+/ to match digits in string, .replace() matched digits with newnumber

var str = "http://www.domain.com/foo/1234/bar/";
var newnumber = 5678;
var n = str.match(/\d+/)[0];
str = str.replace(n, newnumber);

Upvotes: 0

castletheperson
castletheperson

Reputation: 33466

Correct, it's because look-behinds aren't supported in JavaScript. Instead you could use an output string that includes the prefix and suffix:

return myhref.replace(/foo\/\d+\/bar/,'foo/newnumber/bar');

If newnumber is a variable, use concatenation:

return myhref.replace(/foo\/\d+\/bar/,'foo/' + newnumber + '/bar');

Upvotes: 1

awdk
awdk

Reputation: 1601

you could use:

myhref.replace(new RegExp("\/[0-9]*\/", "g"), "/newnumber/")

EDIT: if you want to replace the number by a "newnumber" only if it is between foo and bar then you should add those at RegExp as well as follows. The code above is going to replace the number without verifying it.

myhref.replace(new RegExp("foo\/[0-9]*\/bar", "g"), "foo/newnumber/bar")

Upvotes: 0

Related Questions