export const makeBold = (item, searchText) => {
// searchText = what??
const re = new RegExp(`[${searchText}]`, "g");
return item.replace(re, `<span className="searchTextStyle"> what?? </span>`);
};
"
I want to find the string "what??" However, special characters such as "??" exist and cannot be found properly. I currently used a method of putting it inside the [], but all the strings change one by one. If there is a regx in which all the characters in brackets match, please help.
CodePudding user response:
You should escape string for regex expression. Example below
const text = 'what?? do you want from me?';
const searchText = 'what??';
const regex = new RegExp(regexExpEscape(searchText), 'g');
const replacedText = text.replace(regex, `<span>${searchText}</span>`);
console.log(replacedText);
function regexExpEscape(str) {
return str.replace(/[-[\]{}()* !<=:?.\/\\^$|#\s,]/g, '\\$&');
}
CodePudding user response:
If you're replacing literal strings, there's no need to use regular expressions to begin with.
Just use replaceAll()
with a string parameter instead of a regular expression:
const text = 'what?? do you want from me?';
const searchText = 'what??';
const replacedText = text.replaceAll(searchText, `<span>${searchText}</span>`);
console.log(replacedText);