js去除html轉義字元
用正則及string.replace()方法實現。
parsehtml.js
export
const
parsehtml
=(content)
=>
;const contentwithouttag = content.
replace
(tagreg,'')
;const contentwithonlyonespace = contentwithouttag.
replace
(/ /g
,' ');
return contentwithonlyonespace.
replace
(escapereg,
(all, t)
=> escapeelements[t]);
};
簡單說一下js的replace方法,這方法非常強大。
1、替換
2、替換(全域性+區分大小寫)const str =
'hello, world!'
;str.
replace
(/hello/
,'hi');
// hi, world!
3、換位置const str =
'hello, hello, hello, world!'
;// 引數i忽略大小寫,g全域性
str.
replace
(/hello/ig
,'hi');
// hi, hi, hi, world!
4、第2引數為乙個方法const name =
"doe, john"
;name.
replace
(/(\w+)\s*, \s*(\w+)/
,"$2 $1");
// john doe
5、方法的引數中有轉義const str =
'hello, hello, hello, world!'
;str.
replace
(/hello/
,(all, t)
=> console.
log(all +
'...'
+t))
;// hello...7
// str: 'hello, undefined, hello, world!'
let st =
'hello world'
;st.
replace
(/&(nbsp|le);/ig
,(all, t)
=> console.
log(all +
'...'
+t))
;// ...nbsp 當正則中帶有或,返回的不是index而是值
// st:'helloundefinedworld'
JS實現HTML標籤轉義及反轉義
今天我用ueditor時候遇到乙個問題 我從資料庫中讀取內容進行編輯的時候,不是有一些html標籤嘛,從資料庫讀出來沒有問題 但是我用asp.net mvc,把讀取出來的內容通過ueditor的api方法賦值到編輯區域的時候html標籤被轉義了 比如 變為了 我跟蹤 看後端取到的資料沒有問題,返回到...
js對HTML字元轉義與反轉義
注意 在編寫html時,經常需要轉義,才能正常顯示在頁面上。並且,還可以防止xss。解決方案 一,使用正則 使用正則轉碼 var value document.getelementbyid input value.trim 對使用者輸入進行轉義 value value.replace g,value...
JS對HTML實體字元轉義和反轉義
一 名詞解釋 html實體字元 由於在html中有些符號是預留的,比如在html中不能直接使用尖括號 或 會被誤認為標籤符號。所以需要通過html實體字元去進行替換 html實體字元兩種形式 eg 小於號的html實體字元顯示方式 數字形式 實體名形式 注意 使用實體名而不是數字的好處是,名稱易於記...