Home > Web Front-end > JS Tutorial > body text

How to convert HTML escape characters with JS

高洛峰
Release: 2017-03-12 17:57:48
Original
1928 people have browsed it

//去掉html标签

function removeHtmlTab(tab) {
 return tab.replace(/<[^<>]+?>/g,&#39;&#39;);//删除所有HTML标签
}
Copy after login

//普通字符转换成转意符

function html2Escape(sHtml) {
 return sHtml.replace(/[<>&"]/g,function(c){return {&#39;<&#39;:&#39;&lt;&#39;,&#39;>&#39;:&#39;&gt;&#39;,&#39;&&#39;:&#39;&amp;&#39;,&#39;"&#39;:&#39;&quot;&#39;}[c];});
}
Copy after login

//转意符换成普通字符

function escape2Html(str) {
 var arrEntities={&#39;lt&#39;:&#39;<&#39;,&#39;gt&#39;:&#39;>&#39;,&#39;nbsp&#39;:&#39; &#39;,&#39;amp&#39;:&#39;&&#39;,&#39;quot&#39;:&#39;"&#39;};
 return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
}
Copy after login

// 转成空格

function nbsp2Space(str) {
 var arrEntities = {&#39;nbsp&#39; : &#39; &#39;};
 return str.replace(/&(nbsp);/ig, function(all, t){return arrEntities[t]})
}
Copy after login

//回车转为br标签

function return2Br(str) {
 return str.replace(/\r?\n/g,"<br />");
}
Copy after login

//去除开头结尾换行,并将连续3次以上换行转换成2次换行

function trimBr(str) {
 str=str.replace(/((\s| )*\r?\n){3,}/g,"\r\n\r\n");//限制最多2次换行
 str=str.replace(/^((\s| )*\r?\n)+/g,&#39;&#39;);//清除开头换行
 str=str.replace(/((\s| )*\r?\n)+$/g,&#39;&#39;);//清除结尾换行
 return str;
}
Copy after login

// 将多个连续空格合并成一个空格

function mergeSpace(str) {
 str=str.replace(/(\s| )+/g,&#39; &#39;);
 return str;
}
Copy after login

The above is the detailed content of How to convert HTML escape characters with JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!