Because ( and ) (and several other characters) have special meaning in regular expressions, and you haven't escaped them. You'd need to pass in "\\(parentheses\\)": The first backslash escapes the second in the string literal so that the string actually contains a backslash; that backslash in the string escapes the ( and ).
Example:
function boldString(str, find) {
var re = new RegExp(find, 'g');
return str.replace(re, '<b>' + find + '</b>');
}
console.log(boldString("this is for testing purpose","testing"));
console.log(boldString("testing with (parentheses)","\\(parentheses\\)"));
Of course, without changing your boldString's inputs, that's going to include the backslashes in the output as well. As melpomene pointed out in a comment, you can fix that by using $& as the replacement, which will be the text matched by the exppression:
function boldString(str, find) {
var re = new RegExp(find, 'g');
return str.replace(re, '<b>$&</b>');
}
console.log(boldString("this is for testing purpose","testing"));
console.log(boldString("testing with (parentheses)","\\(parentheses\\)"));
If you're accepting end-user input, this question's answers have functions you can use to add any necessary escapes. For instance, using the one from the currently-accepted answer:
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
function boldString(str, find) {
var re = new RegExp(RegExp.escape(find), 'g');
return str.replace(re, '<b>' + find + '</b>');
}
console.log(boldString("this is for testing purpose","testing"));
console.log(boldString("testing with (parentheses)","(parentheses)"));