問題描述:
有這樣的一段字符串:
"<p class='test' id='wise'>123 4>5<6 789<br>hello<span title='hello' style='width: 200px;height:100px;' src='//www.wisewrong.com/img/123.png'>world</span></p>"
這是一段包含了 html 標簽信息的富文本,現在需要將其中的文本內容處理為全大寫
解決方案:
function superTrim(str) { // 匹配標簽之間的文本
const reg = /(?<=>)(.|\s)*?(?=<\/?\w+[^<]*>)/g; return str.replace(reg, s => s.toUpperCase()); }
const str = "<p class='test' id='wise'>123 4>5<6 789<br>hello<span title='hello' style='width: 200px;height:100px;' src='//www.wisewrong.com/img/123.png'>world</span></p>"; superTrim(str); // "<p class='test' id='wise'>123 4>5<6 789<br>HELLO<span title='hello' style='width: 200px;height:100px;' src='//www.wisewrong.com/img/123.png'>WORLD</span></p>"
重點在於正則的編寫,這里推薦一個大佬自己做的專門交流正則的社區
其次需要利用字符串的 replace 函數,當第一個入參是正則的時候,第二個參數可以用函數的形式來接受正則的匹配結果,且這個函數的返回值會用來替換被正則匹配到的字符串
基於這個特性,只要正則匹配到了字符串,就可以隨便處理了
這里只是舉了全大寫的例子,實際上還可以做簡繁轉換、文本格式化等復雜功能