Dynamically add <wbr> tag before punctuation

I am trying to figure out how to add a tag <wbr>

before punctuation on an email address dynamically using jQuery.

I am guessing there must be a way to scan a string for "." or "@" and put that tag right before it, but I couldn't figure it out.

I tried two different methods, which were the only solutions I could find after looking 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: (first try)

$( ".test" ).click(function() {
  $('.some-special-classname').html().replace(/@/g,"<wbr>@");
  $('.some-special-classname').html().replace(/./g,"<wbr>.");
});

      

Javascript: (second try)

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;
}

      

+3


source to share


2 answers


Can be used html(function(index, oldhtml)

to analyze and update existing content

$('.some-special-classname').html(function(_, oldhtml){
      return oldhtml.replace(/([@.])/g,"<wbr>$1");
});

      



This will also loop through the collection and treat them as instance specific if there are multiple match items in the selector

Ref: html (fn) docs

+2


source


You are almost doing the replacement correctly, but you are not actually 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 change from regex to /([@.])/g

so you don't have to write two separate replacement lines. (thanks @ DJDavid98 for editing)

+2


source







All Articles