Adding HREFs to document's contents whenever regex appears in Javascript
I'd like to find every occurrence of "needle/variable" in the document's contents and replace it with "<a href="blahblah.com/needle/variable/">needle/variable</a>".
I'm trying to use:
document.body.innerHTML = document.body.innerHTML.replace(/(needle\/(variable))/g, '<a href="http://www.blahblah.com/' + $2 + '"> '+$2+' </a>');
but for some reason it's not capturing the $1 and $2. Also, is there a bette开发者_Python百科r way to be doing this? The content "needle/variable" that I'm looking at is not guaranteed to be anywhere specific, it could be anywhere in the document.
RegExp in Javascript doesn't map $1
, $2
, etc to actual variables named $1
or $2
. Instead, you need to put those in quotes:
document.body.innerHTML.replace(/(needle\/(variable))/g, '<a href="http://www.blahblah.com/$2">$2</a>');
精彩评论