Collins Collins - 2 months ago 6
Javascript Question

jQuery take number from string and append html with extracted number

I have the following jQuery which adds a small span after the message icon to allow a small notification bubble to show, but using the method below, if a user gets more than 5 messages, it doesnt show. Technically a user could have an unlimited number of message sent to them, but rather than copy and paste this a hundred times...
What I would like to do is copy the "Messages (1 new)" string, take the number out of the string as "1" and then append a span like this... "1

jQuery('#block-privatemsg-privatemsg-menu .content li.last a:contains("Messages (1 new)")').append( "<span>1</span>" );
jQuery('#block-privatemsg-privatemsg-menu .content li.last a:contains("Messages (2 new)")').append( "<span>2</span>" );
jQuery('#block-privatemsg-privatemsg-menu .content li.last a:contains("Messages (3 new)")').append( "<span>3</span>" );
jQuery('#block-privatemsg-privatemsg-menu .content li.last a:contains("Messages (4 new)")').append( "<span>4</span>" );
jQuery('#block-privatemsg-privatemsg-menu .content li.last a:contains("Messages (5 new)")').append( "<span>5</span>" );


enter image description here

heres the html, but its not easy to change as its generated by a cms module.

<ul>
<li class="first"><a href="/messages/new">Write new message</a></li>
<li class="last"><a href="/messages">Messages (2 new)</a></li>
</ul>

Answer

You may use .append( function ) like in:

jQuery('li.last a').append(function(i, h) {
  var n = h.match(/^\D*(\d)\D*$/);
  return (n == null) ? null :  $('<span>', {text: n[1]});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul>
    <li class="first"><a href="/messages/new">Write new message</a></li>
    <li class="last"><a href="/messages">Messages (2 new)</a></li>
</ul>