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?
Asked
Active
Viewed 1,790 times
0

Sebastian Simon
- 18,263
- 7
- 55
- 75

Chozen
- 299
- 1
- 4
- 18
-
3Have you tried to do it on your own? – Achrome Jul 06 '13 at 01:30
-
1Of 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 Answers
2
Assuming the string will only have one set of digits:
function wrapNum(str) {
return str.replace(/\d+/, '<span>$&</span>');
}

Jason
- 51,583
- 38
- 133
- 185