pedmillon pedmillon - 6 months ago 44
jQuery Question

jQuery replace string of an element

I'd like to replace character "@" by "(at)" within all span tags that contain @ character.
Is there anything like



The code snippet that you have posted is one of the options. But you need to reset the text content of the element.

$('span:contains("@")').text(function(_, text) {
     return text.replace(/@/g, '(at)');

Here is a non-jQuery alternative:

[]'span'), function(span) {
    if ( span.textContent.includes('@') ) {
       span.textContent = span.textContent.replace(/@/g, '(at)');

Please note that resetting .textContent can be destructive if the element has child elements. In that case you can reset the html content of the element (.innerHTML) or better, filter the text nodes of the element.