0

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Chozen
  • 299
  • 1
  • 4
  • 18
  • 3
    Have you tried to do it on your own? – Achrome Jul 06 '13 at 01:30
  • 1
    Of course there is a way! It depends on what this 20 can be. Numbers, worsds etc' – raam86 Jul 06 '13 at 01:33
  • @AshwinMukhija I wouldn't ask the question if I knew how to do it on my own now would I? – Chozen Jul 08 '13 at 15:53
  • Mostly a duplicate of [regex - Javascript replace with reference to matched group? - Stack Overflow](https://stackoverflow.com/questions/1234712/javascript-replace-with-reference-to-matched-group). – user202729 Aug 16 '21 at 13:56

2 Answers2

2

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

raam86
  • 6,785
  • 2
  • 31
  • 46
2

Assuming the string will only have one set of digits:

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

Demo | .replace() Documentation

Jason
  • 51,583
  • 38
  • 133
  • 185