[英]How to wrap a tag around a tag in a string - Javascript
我有一個字符串。 說它看起來像這樣:
<!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>>
使用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>>');
.tag { color: red; }
我將分兩步使用String.replace
...
str.replace(/</g,'<<span class="tag">').replace(/>/g,'</span>>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.