替换javascript中的字符串回调函数

时间:2018-11-20 08:50:42

标签: javascript

我有一个很大的html字符串,类似

<p>content</p>
<img src="example.jpg"/>
<p>another paragraph</p>
<a href="https://example.com/about-me.html?q=23424">about</a>
<a href="https://example.com/blog-link-1.html?q=123>blog</a>

,我要做的是清理链接,但返回整个html字符串。我可以使用正则表达式来清理链接(在?q = 123之后删除),

const str = `<p>content</p>
<p>another paragraph</p>
<a href="https://example.com/about-me.html?q=23424">about me</a>
<br />
<a href="https://example.com/blog-link-1.html?q=123">blog</a>`
const result = str.replace(/https.*.html/g ,function(a) {
  return a //what to do here?
})
console.log(result)
$('#content').html(result)

但是我无法将清理后的链接替换回文档字符串中。

演示http://jsfiddle.net/ofbe3cr7/

1 个答案:

答案 0 :(得分:0)

您不需要替换器功能-而是捕获 URL在组中的第一部分,然后 match 其余URL以负号显示设置,然后将整个匹配项替换为第一个匹配的组(即URL的第一部分):

const str = `<p>content</p>
<p>another paragraph</p>
<a href="https://example.com/about-me.html?q=23424">about me</a>
<br />
<a href="https://example.com/blog-link-1.html?q=123">blog</a>`
const result = str.replace(/(https.*?\.html)[^"]+/g, '$1')
$('#content').html(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

也就是说,单独使用jQuery而不是仅仅 HTML字符串上的正则表达式会更加优雅和可控制:使用<a>查找.find s ,并根据需要替换其href

const str = `<p>content</p>
<p>another paragraph</p>
<a href="https://example.com/about-me.html?q=23424">about me</a>
<br />
<a href="https://example.com/blog-link-1.html?q=123">blog</a>`
const $html = $(str);
$html.find('a').each((_, a) => {
  a.href= a.href.replace(/(https.*?\.html)[^"]+/g, '$1')
});
$('#content').html($html)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>