简体   繁体   中英

Wrap specific part of string with HTML element

Lets say I have a headline (h1) that says:

The 20 Most Useful Users on Stack Exchange

Is there a way to add a element only around the "20" and only the "20" with jQuery or pure Javascript?

Assuming the string will only have one set of digits:

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

Demo | .replace() Documentation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM