Find and replace jQuery HTML string

Links from the database are site names and rendering on the page " Interesting article : Author" - but sometimes the link is the question " Where is China ? : GoogleMaps". ?: looks silly, so I wanted to replace the HTML ?</span>: with ?</span> .

Here is the jQuery I developed:

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

But this does not actually replace it in the DOM. How to get this line to actually change the page?

+7
source share
2 answers

I would 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 verify that the last character in the span is in the array ['?','!','.'] , And if there is one, then remove : from nextSibling 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 .

Literature:

+19
source

You can also use regex:

 var rx = new RegExp('(?![^<&]+[>;])' + searchString, 'gi'); $('#relatedinfo').html(function (i, html) { return html.replace(rx, '<b>$&</b>') }); 

source: jQuery for finding / replacing html text if not inside an html tag other than P, DIV, SPAN, TD

0
source

All Articles