needle/variable</a>\"." />
开发者

Adding HREFs to document's contents whenever regex appears in Javascript

开发者 https://www.devze.com 2023-04-10 22:35 出处:网络
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'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>');
0

精彩评论

暂无评论...
验证码 换一张
取 消