为每个字母添加跨度,但避免使用javascript生成html标签

时间:2018-12-02 14:44:34

标签: javascript html regex string

我有一个字符串

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">&lt;</span>
<span class="letter">b</span>
<span class="letter">r</span>
<span class="letter">&gt;</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

2 个答案:

答案 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。