如何使用常规exp?
用“span”替换文本中的每个单词var text = "1:393 1:838 3:936 1:998 1:1398 1:1652 1:1718 1:1806"
final op = "<span class="word">1:393</span><span class="word">1:838</span><span class="word">3:936</span><span class="word">1:998</span><span class="word">1:139</span>...."
答案 0 :(得分:3)
如果分隔符始终是单个空格,则不需要正则表达式,只需分隔空格(或\b
如果你想要一个正则表达式),添加一些标记,然后重新加入。
var text = "1:393 1:838 3:936 1:998 1:1398 1:1652 1:1718 1:1806";
var op = text.split(' ').map(function(w) {
return '<span class="word">' + w + '------</span>';
}).join('');
document.body.innerHTML = op;
.word {color : red}
答案 1 :(得分:1)
var op = '<span class="word">' + text.split(' ').join('</span><span class="word">') + '</span>'
答案 2 :(得分:1)
使用String#replace
。
const text = "1:393 1:838 3:936 1:998 1:1398 1:1652 1:1718 1:1806";
const result = text.replace(/\d:\d+/g, '<span class="word">$&</span>');
console.log(result);
&#13;
答案 3 :(得分:0)
这是您所需要的(https://jsfiddle.net/6r005vgf/3/):
var text = "1:393 1:838 3:936 1:998 1:1398 1:1652 1:1718 1:1806";
//var final = "<span class='word'>1:393</span><span class='word'>1:838</span><span class='word'>3:936</span><span class='word'>1:998</span><span class='word'>1:139</span>....";
var final_test = "<span class='word'>" + text.replace(/\s+/g, "</span><span class='word'>") + "</span>";
//alert(final);
alert(final_test);