Find and replace HTML string with jQuery

2019-02-16 17:30发布

问题:

Links from the database are website titles and render on the page "Interesting Article: Author" - but occasionally the link is a question "Where's China?: GoogleMaps". The ?: looks silly so I wanted to replace the HTML ?</span>: with ?</span>.

Here is the jQuery I worked out:

$('#relatedinfo ul li a').html().replace('?</span>:','?</span>');

But this doesn't actually replace it in the DOM. How do I get that string to actually change the page?

回答1:

I'd suggest:

$('#relatedinfo ul li a').html(function(index,html){
    return html.replace(/<\/span>(\:)/,'');
});

JS Fiddle demo.

Or even:

$('#relatedinfo ul li a').text(function(index,text){
    return text.replace(':','');
});

JS Fiddle demo.

An updated approach is to check that the last character in the span is in the array of ['?','!','.'] and, if it is, then to remove the : from the nextSibling's nodeValue:

$('#relatedinfo ul li a span').text(function(index,text){
    var lastchar = text.split('').pop();
    if (['?','!','.'].indexOf(lastchar) > -1) {
        this.nextSibling.nodeValue = this.nextSibling.nodeValue.replace(':','');
    }
});

JS Fiddle demo.

References:

  • html().
  • String.replace().
  • text().


回答2:

You can also use regex :

var rx = new RegExp('(?![^<&]+[>;])' + searchString, 'gi');

$('#relatedinfo').html(function (i, html) {
   return html.replace(rx, '<b>$&</b>')
});

source : jQuery to Find/Replace html text when not inside an html tag other than P, DIV, SPAN, TD