简体   繁体   English

用HTML元素包装字符串的特定部分

[英]Wrap specific part of string with HTML element

Lets say I have a headline (h1) that says: 可以说我有一个标题(h1):

The 20 Most Useful Users on Stack Exchange Stack Exchange上20个最有用的用户

Is there a way to add a element only around the "20" and only the "20" with jQuery or pure Javascript? 有没有一种方法可以仅使用jQuery或纯Javascript在“ 20”和“ 20”之间添加元素?

Assuming the string will only have one set of digits: 假设该字符串只有一组数字:

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

Demo | 演示 | .replace() Documentation .replace()文档

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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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