var x = '#google'; // or '@google' or '%google'
var pattern = new RegExp('(^|\\s)' + x);
var result = txt.replace(pattern, '$1' + 'MyNewWord');
this code works fine to replace #google
if I use & or @ instead of # it works fine
only it doesn’t work when I use $ instead of # so the following code doesn’t work properly
var x = '$google';
var pattern = new RegExp('(^|\\s)' + x);
var result = txt.replace(pattern, '$1' + 'MyNewWord');
ps I used new RegEXP because x will be user input.
$is a special character in a RegExp so you need to escape it: