Home  >  Article  >  Web Front-end  >  How to convert HTML escape characters with JS

How to convert HTML escape characters with JS

高洛峰
高洛峰Original
2017-03-12 17:57:481930browse

//去掉html标签

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

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

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];});
}

//转意符换成普通字符

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];});
}

// 转成空格

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

//回车转为br标签

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

//去除开头结尾换行,并将连续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;
}

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

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

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!

Statement:
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