我有一个字符串
var string = "Selected<br>Works"
我需要用<span></span>
包装每个字母,避免在范围内包装<br>
标签。正则表达式可以吗?
我做到了:
'Selected<br>Works'.replace(/\S/g, '<span class="letter">$&</span>')
哪个返回:
<span class="letter">S</span>
<span class="letter">e</span>
<span class="letter">l</span>
<span class="letter">e</span>
<span class="letter">c</span>
<span class="letter">t</span>
<span class="letter">e</span>
<span class="letter">d</span>
<span class="letter"><</span>
<span class="letter">b</span>
<span class="letter">r</span>
<span class="letter">></span>
<span class="letter">W</span>
<span class="letter">o</span>
<span class="letter">r</span>
<span class="letter">k</span>
<span class="letter">s</span>
所需结果是:
<span class="letter">S</span>
<span class="letter">e</span>
<span class="letter">l</span>
<span class="letter">e</span>
<span class="letter">c</span>
<span class="letter">t</span>
<span class="letter">e</span>
<span class="letter">d</span>
<br>
<span class="letter">W</span>
<span class="letter">o</span>
<span class="letter">r</span>
<span class="letter">k</span>
<span class="letter">s</span>
其他字符串示例为:
Art Direction<br>Creative Concept<br>UX/UI Design
Digital Branding<br>Website
答案 0 :(得分:1)
您可以使用<br>
分隔符分割字符串,以返回包含字母的多个数组。然后使用.map()
和.replace()
将每个字母包装在<span></span>
中。最后用<br>
var string = "Selected<br>Works";
var newStr = string.split("<br>").map(function(val){
return val.replace(/(\S)/g, "<span>$1</span>");
}).join("<br>");
console.log(newStr);
document.body.innerHTML = (newStr);
span:nth-child(even) {color: blue}
span:nth-child(odd) {color: red}
答案 1 :(得分:1)
您可以将replace
与前瞻性的正则表达式一起使用:
var string = "Selected<br>Works",
result = string.replace(/(?![^<]*>)[^<]/g, c => `<span>${c}</span>\n`);
console.log(result);
这还将跳过其他标签,例如<p>
或</canvas>
。尽管如此,它仍无法处理更复杂的HTML(包括脚本,注释等),而正则表达式不适合使用这些HTML。