Chozen
Chozen

Reputation: 299

Wrap specific part of string with HTML element

Let’s say I have a headline (<h1>) that says The 20 Most Useful Users on Stack Exchange. Is there a way to add a <span class="numbers"></span> element only around the 20 with JavaScript?

Upvotes: 0

Views: 1853

Answers (2)

raam86
raam86

Reputation: 6871

Easiest way to achieve this is:

$('h1').each(function (_, el) {
var $this = $(el);
var h1Content = $this.html();
$this.html(h1Content.replace(/(\d+)/, '<span>$1</span>'));
});

This assumes you want the first number. DEMO

Upvotes: 2

Jason
Jason

Reputation: 52533

Assuming the string will only have one set of digits:

function wrapNum(str) {
    return str.replace(/\d+/, '<span>$&</span>');
}

Demo | .replace() Documentation

Upvotes: 2

Related Questions