【发布时间】:2015-04-14 08:52:15
【问题描述】:
我在一个 javascript 变量中有一段文本,其中包含多个锚点、区域和链接标签。我想用其他链接替换链接标签以外的所有href链接。例如,我当前的正则表达式匹配所有不包含 (mailto:) 和 (abc-url) 的 href
var r_domain = 'testlink.com';
var s = 'someencryptedstring';
var pattern = /href[\s]*=[\s]*('|")(?!mailto:)(?!#)((?:(?!\abc-url\b)[^('|")])*)('|")/ig;
var replace_pattern = 'href=\"http://'+r_domain+'/link.php?str='+s+'&mailin-url=$2"';
var body = '<a href="http://example.com" >abc</a> test data <a href="http://test.com/test.php?str=someencryptedstring&abc-url=http://cdf.com" > link </a> test last <link rel="stylesheet" href="http://csslink.com/forms.css" type="text/css" media="screen, projection" /> area test <a href="http://example_1.com" > xyz </a>';
var re = new RegExp(pattern);
var replaced = body.replace(re , replace_pattern);
console.log(replaced);
它应该只替换以下链接:
href="http://example.com"
href="http://example_1.com"
它不应取代以下链接:
href="http://test.com/test.php?str=someencryptedstring&abc-url=http://cdf.com"
href="http://csslink.com/forms.css"
输出应该如下 (console.log(replaced);):
<a href="http://testlink.com/link.php?str=someencryptedstring&mailin-url=http://example.com" >abc</a> test data <a href="http://test.com/test.php?str=someencryptedstring&abc-url=http://cdf.com" > link </a> test last <link rel="stylesheet" href="http://csslink.com/forms.css" type="text/css" media="screen, projection" /> area test <a href="http://testlink.com/link.php?str=someencryptedstring&mailin-url=http://example_1.com" > xyz </a>
【问题讨论】:
标签: javascript regex node.js