1

您将如何使用正则表达式或 javascript/jQuery 中的替代形式在元素之间插入子字符串?

例如我有以下字符串:

This is a string 015 with numbers 1486453 randomly 10 inserted between words 0954

如果我的正则表达式要查找所有数字,则结果如下:

This is a string <span>015</span> with numbers <span>1486453</span> randomly <span>10</span> inserted between words <span>0954</span>

4

2 回答 2

5
var testStr = 'This is a string 015 with numbers 1486453 randomly 10 inserted between words 0954';    
var result = testStr.replace(/(\d+)/gi, '<span>$1</span>');
于 2012-07-26T03:28:06.503 回答
0
var str = $el.text();
$el.html(str.replace(/\d+/g, "<span>$&</span>"));

如果您的元素已经包含 html 节点,它会变得更加复杂。您需要构建一个 DOM 迭代器 - 请参阅此答案

于 2012-07-26T03:38:41.843 回答