Dynamically Add Tag Before Punctuation
I'm trying to figure out how to add a tag before punctuation in an email address, dynamically using jQuery. I imagine there must be a way to scan the string for a '.' o
Solution 1:
Can use html(function(index, oldhtml)
to parse and update existing content
$('.some-special-classname').html(function(_, oldhtml){
return oldhtml.replace(/([@.])/g,"<wbr>$1");
});
This will also loop over a collection and treat them as instance specific if there are more than one matching elements in selector
Reference: html(fn) docs
Solution 2:
You are almost doing the replacement correctly but actually not editing the DOM.
var$elem = $('.some-special-classname');
var formattedString = $elem.html().replace(/([@.])/g,"<wbr>$1");
$elem.html(formattedString); //this is what you are missing!
Also note the regular expression change to /([@.])/g
so you don't need to write 2 separate lines for replacing. (thanks @DJDavid98 for the edit)
Post a Comment for "Dynamically Add Tag Before Punctuation"