什么是最简单的JavaScript HTMLEncode库/函数实现? [英] What is the most simple JavaScript HTMLEncode lib/function implementation?

查看:102
本文介绍了什么是最简单的JavaScript HTMLEncode库/函数实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个js函数或lib,它可以将等特殊字符转换为& trade; ,有人知道吗?我正在寻找我能找到的最简单的一个。

这些是 HTML命名实体,它们不是最佳解决方案 - 更好地使用数字实体。为什么数字实体更好?因为您没有像©& copy; 之类的地图。所有你需要的是一个字符本身。

  function abc(input){
var output =;
var allowedChars =0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM;

for(var i = 0; i< input.length; i ++){
var char = input.charAt(i);
var charCode = input.charCodeAt(i);

if(isNaN(charCode)){
continue;
}

if(allowedChars.indexOf(char)> -1){
output + = char;
} else {
output + =&#+ charCode +;;
}
}

返回输出;
}

alert(abc(Hello world!?™汉)); // Hello&#32; world&#32;&#169;&#8482;&#27721


I'm looking for a js function or lib that'll convert special chars like to &trade;, does anyone know of any? I'm looking for the simplest one that I can find.

解决方案

Those are HTML named entities and they're not a best solution — better use a numerical entities. Why numerical entities are better? Cause you don't have any map like ©&copy;. All you need is a character itself.

function abc(input) {
    var output = "";
    var allowedChars = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";

    for (var i = 0; i < input.length; i++) {
         var char     = input.charAt(i);
         var charCode = input.charCodeAt(i);

         if (isNaN(charCode)) {
             continue;
         }

         if (allowedChars.indexOf(char) > -1) {
             output += char;
         } else {
             output += "&#" + charCode + ";";
         }
    }

    return output;
}

alert(abc("Hello world! ©™汉")); // Hello&#32;world&#33;&#32;&#169;&#8482;&#27721

这篇关于什么是最简单的JavaScript HTMLEncode库/函数实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆