I'm trying to figure out how to add a <wbr>
tag before punctuation in an email address, dynamically using jQuery.
I imagine there must be a way to scan the string for a "." or "@" sign and place this tag right before it, but I haven't been able to figure it out.
I've attempted two different methods which were the only solutions I was able to come up with after searching for solutions:
HTML:
<div class="container">
<span class="some-special-classname">
verylongfirstname.verylonglastname@prettylongemailaddress.com
</span>
<br /> <br />
<button class="test">Test Button</button>
</div>
CSS
wbr:after {
content:"\00200B";
}
.container {
margin: 0 auto;
max-width: 400px;
padding : 10px;
border: 1px solid #bbb;
}
Javascript: (1st. attempt)
$( ".test" ).click(function() {
$('.some-special-classname').html().replace(/@/g,"<wbr>@");
$('.some-special-classname').html().replace(/./g,"<wbr>.");
});
Javascript: (2nd. attempt)
var str = $('.some-special-classname').val();
str.replace(/@/g,'<wbr>@');
function myFunction() {
var str = $('.some-special-classname').val();
var n = str.indexOf(".");
document.getElementById("demo").innerHTML = n;
}
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.