用HTML元素包装字符串的特定部分 [英] Wrap specific part of string with HTML element

查看:112
本文介绍了用HTML元素包装字符串的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说一个标题(h1)如下:

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

Stack Exchange上20个最有用的用户

The 20 Most Useful Users on Stack Exchange

有没有一种方法可以仅在jQuery或纯Javascript的"20"附近添加元素,并且仅在"20"附近添加元素?

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

推荐答案

最简单的方法是:

$('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

这篇关于用HTML元素包装字符串的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆