pedmillon pedmillon - 1 year ago 170
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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download