javascript regexp正面看后面动态地替换/包装URL中的文本

时间:2017-12-04 21:54:26

标签: javascript jquery

使用jQuery / Javascript,我希望匹配多个容器中的文本,并在使用URL中匹配的文本时在文本周围包装一个链接。

输入HTML:

<div id="sampleText">
The dog jumped over the fence id:12345-6789 and ran into another fence id:98765-4321.
</div>

<div>
The dog continued to jump over fence id:12345-6789 and again ran into another fence id:98765-4321.
</div>

输出HTML:

<div>
The dog jumped over the fence id:<a href="123.45678.com.com?id=12345-6789">12345-6789</a> and ran into another fence id:<a href="123.45678.com?id=98765-4321">98765-4321</a>.
</div>

<div>
The dog continued to jump over fence id:<a href="123.45678.com.com?id=12345-6789">12345-6789</a> and again ran into another fence id:<a href="123.45678.com?id=98765-4321">98765-4321</a>.
</div>

这是我到目前为止(不工作)......

$("div:contains('fence id:')").html(function(_,html){
     var rx = new RegExp('fence id:[0-9A-Z-]+','gi');
     return html.replace(rx, '<a href="123.45678.com?id='+$1+'">'+$1+'</a>');
});

1 个答案:

答案 0 :(得分:1)

你非常接近!

首先,您需要确保正则表达式实际上是使用()来创建捕获组来捕获ID文本:

var rx = new RegExp('fence id:([0-9A-Z-]+)','gi');

其次,当使用$1引用捕获组时,您实际上只想将其包含在替换字符串中,而不是将其作为变量处理:

return html.replace(rx, '<a href="123.45678.com?id=$1">$1</a>');

$("div:contains('fence id:')").html(function(_,html){
     var rx = new RegExp('fence id:([0-9A-Z-]+)','gi');
     return html.replace(rx, '<a href="123.45678.com?id=$1">$1</a>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sampleText">
The dog jumped over the fence id:12345-6789 and ran into another fence id:98765-4321.
</div>

<div>
The dog continued to jump over fence id:12345-6789 and again ran into another fence id:98765-4321.
</div>