简体   繁体   中英

replace string callback function in javascript

I have a big html string, something like

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

and what I have to do is to clean the links but return the entire html string. I can use regex to do the cleaning for the link (remove after ?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)

but I failed to replace the cleaned links back into the document string.

Demo http://jsfiddle.net/ofbe3cr7/

You don't need a replacer function - instead, capture the first part of the URL in a group, then match the rest of the URL with a negative character set, and then replace the entire match with the first matched group (that is, the first part of the 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> 

That said, it would be more elegant and controlled to do this with jQuery alone, and not just a regex on an HTML string: find <a> s with .find , and replace their href s as needed:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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