Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace HTML string with jQuery

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?

like image 739
Daniel Avatar asked Mar 04 '13 14:03

Daniel


People also ask

How to replace a HTML element in jQuery?

To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.

How to change element text using jQuery?

To change text inside an element using jQuery, use the text() method.


1 Answers

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().
like image 102
David Thomas Avatar answered Oct 11 '22 23:10

David Thomas