Inbar Azulay Inbar Azulay - 3 days ago 3
Javascript Question

Regex function not working when one key contains the other key

I've got the following regex function:

for(var key in args) {
var regex = new RegExp('{' + key + '[^}]*}', 'g');
pattern = pattern.replace(regex, args[key]);
}


This makes sure when
args
looks like:

var args: {
name: 'test',
id: '12'
}


And

pattern = "{name}/{id:[0-9]}"


When this function is called,
pattern
will change to
test/12


But when
pattern
look like
{name[a-z]}/{name2[0-9]}
,
name2
gets the same value as
name
when my
args
look like:

var args: {
name: 'test',
name2: '12'
}


How can I edit my code to make
pattern
look like
test/12
?

Answer

Currently you allow any non {-character to follow name, so indeed name2 will be matched as well.

You need to avoid that the regular expression for matching name does not also take name2 as a match. One way of doing that, is to require there is a break in alphanumerical characters after matching name, i.e. you add \b in the regular expression. Since you define the regular expression as a quoted string, you'll need to escape that backslash:

var args = {
  name: 'test',
  name2: '12'
};
var pattern = '{name[a-z]}/{name2[0-9]}';
for(var key in args) {
  var regex = new RegExp('{' + key + '\\b[^}]*}', 'g');
  pattern = pattern.replace(regex, args[key]);
}

console.log(pattern);

Comments