Reputation: 1620
I am trying to replace a particular string using regex.
var replace = {'<RAndom>': "random object"};
I am replacing it using the dynamic regex because i have a lot of objects.
var tagsText = "<RAndom> hellow world";
var regex = new RegExp('\\b(' + Object.keys(replace).join('|') + ')\\b', 'g');
tagsText = tagsText.replace(regex, function(match) {
return replace[match] + match;
});
But it is not working.I think the problem is with the semicolon but i am not sure.The output is again the same.
"<RAndom> hellow world"
Any ideas?
Upvotes: 1
Views: 54
Reputation: 626689
The word boundary \b
and non-word boundary assertion behavior depends on the context. Make it context-independent with unambiguous (^|\W)
and ($|\W)
:
var replace = {'<RAndom>': "random object"};
var tagsText = "<RAndom> hellow world";
var regex = new RegExp('(^|\\W)(' + Object.keys(replace).join('|') + ')(\\W|$)', 'g');
tagsText = tagsText.replace(regex, function(match, g1, g2, g3) {
return replace[g2] ? replace[g2] + match : match;
});
// And just a demo below
document.body.innerHTML = "<pre>" + tagsText.replace(/&/g, '&') + "</pre>";
The (^|\W)
will match the start of string or a non-word character. The ($|\W)
will match the end of the string or a non-word character.
Since we have 3 groups now, we can pass them as arguments to the replace callback. With replace[g2] ? replace[g2] + match : match;
, we first check if there is a value for g2
key, and if yes, perform the replacement. Else, just return the match
.
Upvotes: 1
Reputation: 784898
Problem is presence of \b
(word boundary) on each side that is placed before &
and ;
. Both &
and ;
are not non-word characters and \b
cannot be asserted before and after non-word chars.
You can use \B
instead:
var regex = new RegExp('\\B(' + Object.keys(replace).join('|') + ')\\B', 'g');
and then
tagsText = tagsText.replace(regex, function(match) {
return replace[match] + match;
});
//=> "random object<RAndom> hellow world"
Upvotes: 2