【问题标题】:Regex to get the link in href from the tags other then <link> tag正则表达式从 <link> 标签以外的标签获取 href 中的链接
【发布时间】: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


    【解决方案1】:

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

    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"';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-14
      • 2010-09-21
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2011-04-29
      • 1970-01-01
      相关资源
      最近更新 更多