If you give replace
a string for the first argument, only the first match is replaced. To replace all matches, you have to pass in an regular expression as the first argument, and use the g
flag on it. This replaces all a
s with b
s:
var str = "a a a a";
str = str.replace(/a/g, 'b');
console.log(str); // "b b b b"
So you'll need to create a regular expression for selectedText
. You can do that via new RegExp(selectedText, "g")
:
var res = str.replace(new RegExp(selectedText, "g"),'<b>' + selectedText + '</b>');
...but if selectedText
has any characters in it that have special meaning in a regular expression, you have to escape those. Sadly, JavaScript has no built-in function for doing that, but if you search around you can find several examples of functions to do it. This answer on SO has some options as well.
If we use the RegExp.escape
from this answer to that question (it's a bit overkill, but fairly harmless in its overkill-ness):
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
...then:
var res = str.replace(new RegExp(RegExp.escape(selectedText), "g"),'<b>' + selectedText + '</b>');