我有一个字符串。说它看起来像这样:
<!DOCTYPE html>
<html>
<head>
<title>Web Page</title>
</head>
<body>
<p>Content.</p>
</body>
</html>
如何使输出看起来像这样?
<!DOCTYPE html>
<<span class="tag>html</span>>
<<span class="tag>head</span>>
<<span class="tag>title</span>>Web Page<<span class="tag>/title</span>>
<<span class="tag>/head</span>>
<<span class="tag>body</span>>
<<span class="tag>p</span>>Content.<<span class="tag>/p</span>>
<<span class="tag>/body</span>>
<<span class="tag>/html</span>>
答案 0 :(得分:2)
使用String#replace
方法替换包裹范围内的所有标记。
str.replace(/<(\/?\w+)>/g, '<<span class="tag">$1</span>>');
// or .replace(/(<)(\/?\w+)(>)/g, '$1<span class="tag">$2</span>$3')
var str = `<!DOCTYPE html>
<html>
<head>
<title>Web Page</title>
</head>
<body>
<p>Content.</p>
</body>
</html>`
document.body.innerHTML = str.replace(/<(\/?\w+)>/g, '<<span class="tag">$1</span>>');
&#13;
.tag {
color: red;
}
&#13;
答案 1 :(得分:-1)
我会使用String.replace
...
str.replace(/</g,'<<span class="tag">').replace(/>/g,'</span>>');