3

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;
}
Tara Jensen
  • 65
  • 1
  • 10

2 Answers2

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)

Arash Milani
  • 6,149
  • 2
  • 41
  • 47
  • Thanks Arash! This worked, but when I added additional email addresses it set them all to the same address. I update the [CodePen](http://codepen.io/TLJens/pen/eNgqPo) with this as my "First Solution" button. – Tara Jensen Aug 05 '15 at 00:27
  • Also thanks for editing my question! I voted up your answer since it technically worked given the HTML I had started with. – Tara Jensen Aug 05 '15 at 00:35
2

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

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • 1
    Thank you! This is perfect! Tested it with multiple email addresses and it works on all instances: [CodePen](http://codepen.io/TLJens/pen/eNgqPo) – Tara Jensen Aug 05 '15 at 00:29