繁体   English   中英

RegExp查找标签和变量

[英]RegExp to find tag and variable

您能否更正我的RegExp使其正常工作? 我需要检查我要替换的字符串是否没有被标签包围。

var re = new RegExp("<a\b[^>]*>"+variable+"<\/a>","gi");

您必须先捕获所有链接并自行替换它们:

var variable = "os";
var yourstring= "sdfsdlkjfsd <a href=blux> os</a> sdfsdflkjsdf os";

var re = new RegExp("(<a\\b[^>]*>(?:[^<]+|<(?!/a>))*</a>)|("+variable+")","gi");

function replacer(match, p1, p2){
    var replacement = "glups";
    return (p1)? p1 : replacement;
};
var result = yourstring.replace(re, replacer);
console.log(result);

图案细节:

(?:[^<]+|<(?!/a>))*描述之间的“a”的标签的内容的装置,以及

(?:          # open a non capturing group
    [^<]+    # all characters except < one or more times
  |          # OR
    <(?!/a>) # < not followed by "/a>"
)*           # close the non capturing group and repeat zero or more times

您需要将\\\\b的反斜杠加倍,以使其通过\\b到达正则表达式:

var re = new RegExp("<a\\b[^>]*>"+variable+"<\/a>","gi");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM