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?

4
  • 3
    Have you tried to do it on your own? Commented Jul 6, 2013 at 1:30
  • 1
    Of course there is a way! It depends on what this 20 can be. Numbers, worsds etc' Commented Jul 6, 2013 at 1:33
  • @AshwinMukhija I wouldn't ask the question if I knew how to do it on my own now would I? Commented Jul 8, 2013 at 15:53
  • Mostly a duplicate of regex - Javascript replace with reference to matched group? - Stack Overflow. Commented Aug 16, 2021 at 13:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

2

Assuming the string will only have one set of digits:

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

Demo | .replace() Documentation

1 Comment

Otherwise, just add a global flag: /\d+/g

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.