I have a problem replace certain words started with #. I have the following code
var x="#google",
eval("var pattern = /" + '\\b' + x + '\\b');
txt.replace(pattern,"MyNewWord");
when I use the following code it works fine
var x="google",
eval("var pattern = /" + '\\b' + x + '\\b');
txt.replace(pattern,"MyNewWord");
it works fine
any suggestion how to make the first part of code working
ps. I use eval because x will be a user input.
The problem is that
\brepresents a boundary between a “word” character (letter, digit, or underscore) and a “non-word” character (anything else).#is a non-word character, so\b#means “a#that is preceded by a word character” — which is not at all what you want. If anything, you want something more like\B#;\Bis a non-boundary, so\B#means “a#that is not preceded by a word character”.I’m guessing that you want your words to be separated by whitespace, instead of by a programming-language concept of what makes something a “word” character or a “non-word” character; for that, you could write:
Edited to add: If
xis really supposed to be a literal string, not a regex at all, then you should “quote” all of the special characters in it, with a backslash. You can do that by writing this: