1

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?

1
  • 1
    You should remove the \\bs or replace with (^|\\W) and (\\W|$) respecitively. Commented Apr 21, 2016 at 10:57

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

If a key starts or ends with a word character, this will fail.
Right in that case OP's code would have worked. I guess more details needed from OP about the intent behind \b and more examples.
Or use my solution that is context-independent. Kind of :)
1

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, '&amp;') + "</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.

1 Comment

Thanks for the awesome explanation :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.