Regex从除<link>标签

Regex to get the link in href from the tags other then <link> tag

本文关键字:标签 gt link lt 从除 Regex      更新时间:2023-10-24

我在一个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(已替换);):

<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>

我已经更改了模式和replace_pattern的正则表达式,并保持了其他脚本的原样。它对我来说很好。

模式和replace_pattern的新正则表达式如下:

var pattern = /(<(a|area) [^>]*)href['s]*=['s]*('|")(?!mailto:)(?!#)((?:(?!'abc-url'b)[^('|")])*)('|")/ig;
var replace_pattern = '$1href='"http://'+r_domain+'/link.php?str='+s+'&mailin-url=$4"';