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?
-
3Have you tried to do it on your own?Achrome– Achrome2013-07-06 01:30:08 +00:00Commented Jul 6, 2013 at 1:30
-
1Of course there is a way! It depends on what this 20 can be. Numbers, worsds etc'raam86– raam862013-07-06 01:33:12 +00:00Commented 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?Chozen– Chozen2013-07-08 15:53:48 +00:00Commented Jul 8, 2013 at 15:53
-
Mostly a duplicate of regex - Javascript replace with reference to matched group? - Stack Overflow.user202729– user2027292021-08-16 13:56:17 +00:00Commented Aug 16, 2021 at 13:56
Add a comment
|
2 Answers
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
Comments
Assuming the string will only have one set of digits:
function wrapNum(str) {
return str.replace(/\d+/, '<span>$&</span>');
}
1 Comment
bozdoz
Otherwise, just add a global flag:
/\d+/g