Don't include the slashes when building up the regex as a string:
var regex = new RegExp(word + "(?![^<]*?<\/a>)","g");
Pergunta
I have a string with a variety of html tags in it. For example:
var str = "<div>My text is <a> here</a> and it is <a> very wonderful</a>. For an example of how very great <a> my text is</a>. Please have a look</div>"
I would like to use javascript string.replace() to replace only the words that are not inside of a tag (anchor in this case). It will also depend on user input, so I need to include a variable in the RegExp. I am testing first with string.match(); to verify that I only get one match.
I borrowed the code from javascript regex replace some words with links, but not within existing links and just switched .replace to .match. so I use the following code:
var word = "very";
var regex = new RegExp("/" + word + "(?![^<]*?<\/a>)/g");
console.log(str.match(regex).length);
It returns to me TypeError: titleText.match(...) is null which suggests to me that no matches are found. If I build it like this, however:
console.log(str.match("/very(?![^<]*?<\/a>)/g").length);
I get the expected number of results; in this case, 1;
Any suggestions?
Solução
Don't include the slashes when building up the regex as a string:
var regex = new RegExp(word + "(?![^<]*?<\/a>)","g");