如何在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>
答案 0 :(得分: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>');
答案 1 :(得分:0)
var str = $el.text();
$el.html(str.replace(/\d+/g, "<span>$&</span>"));
如果您的元素已包含html节点,则会变得更复杂。您需要构建DOM迭代器 - 请参阅this answer。