I know my question might look like a duplication for this question, but its not
I am trying to match a class name inside html text that comes from the
Using a regex, this pattern should work for you:
var r = new RegExp("(<\\w+?\\s+?class\\s*=\\s*['\"][^'\"]*?\\b)" + key + "\\b", "i");
# Λ Λ Λ
# |_________________________________________| |
# ____________| |
# [Creating a backreference] |
# [which will be accessible] [Using "i" makes the matching "case-insensitive".]_|
# [using $1 (see examples).] [You can omit "i" for case-sensitive matching. ]
E.g.
var oldClass = "b";
var newClass = "e";
var r = new RegExp("..." + oldClass + "...");
"".replace(r, "$1" + newClass);
// ^-- returns:
"".replace(r, "$1" + newClass);
// ^-- returns:
"".replace(r, "$1" + newClass);
// ^-- returns: // <-- NO change
NOTE:
For the above regex to work there must be no '
or "
inside the class string.
I.e.