是否有人知道如何将特殊字符转换为HTML
中的Javascript
?
示例:
&
(&符号)变为&
。"
(双引号)在"
未设置时变为ENT_NOQUOTES
。'
(单引号)仅在设置'
时变为ENT_QUOTES
。<
(小于)变为<
。>
(大于)变为>
。答案 0 :(得分:202)
我认为最好的方法是使用浏览器的内置HTML转义功能来处理许多情况。为此,只需在DOM树中创建一个元素,并将元素的innerText
设置为您的字符串。然后检索元素的innerHTML
。浏览器将返回HTML编码的字符串。
function HtmlEncode(s)
{
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
试运行:
alert(HtmlEncode('&;\'><"'));
输出:
&;'><"
这种转义HTML的方法也被Prototype JS library使用,但与我给出的简单示例不同。
注意:您仍然需要自己转义引号(双引号和单引号)。您可以使用其他人概述的任何方法。
答案 1 :(得分:68)
你需要一个像
这样的功能return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
但考虑到你对不同处理单/双引号的渴望。
答案 2 :(得分:30)
此通用函数将每个非字母字符编码为其htmlcode(数字):
function HTMLEncode(str) {
var i = str.length,
aRet = [];
while (i--) {
var iC = str[i].charCodeAt();
if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
aRet[i] = '&#'+iC+';';
} else {
aRet[i] = str[i];
}
}
return aRet.join('');
}
答案 3 :(得分:19)
来自Mozilla ......
请注意,charCodeAt将始终返回小于65,536的值。这是因为较高的代码点由一对(较低值)“代理”伪字符表示,这些伪字符用于构成真实字符。因此,为了检查或重现值为65,536及以上的单个字符的完整字符,对于这些字符,不仅需要检索charCodeAt(i),还需要检索charCodeAt(i + 1)(就像检查一样) /再现一个带有两个&gt;字母的字符串。
最佳解决方案
/**
* (c) 2012 Steven Levithan <http://slevithan.com/>
* MIT license
*/
if (!String.prototype.codePointAt) {
String.prototype.codePointAt = function (pos) {
pos = isNaN(pos) ? 0 : pos;
var str = String(this),
code = str.charCodeAt(pos),
next = str.charCodeAt(pos + 1);
// If a surrogate pair
if (0xD800 <= code && code <= 0xDBFF && 0xDC00 <= next && next <= 0xDFFF) {
return ((code - 0xD800) * 0x400) + (next - 0xDC00) + 0x10000;
}
return code;
};
}
/**
* Encodes special html characters
* @param string
* @return {*}
*/
function html_encode(string) {
var ret_val = '';
for (var i = 0; i < string.length; i++) {
if (string.codePointAt(i) > 127) {
ret_val += '&#' + string.codePointAt(i) + ';';
} else {
ret_val += string.charAt(i);
}
}
return ret_val;
}
用法示例:
html_encode("✈");
答案 4 :(得分:18)
创建一个使用字符串replace
function convert(str)
{
str = str.replace(/&/g, "&");
str = str.replace(/>/g, ">");
str = str.replace(/</g, "<");
str = str.replace(/"/g, """);
str = str.replace(/'/g, "'");
return str;
}
答案 5 :(得分:6)
function ConvChar( str ) { c = {'<':'<', '>':'>', '&':'&', '"':'"', "'":''', '#':'#' }; return str.replace( /[<&>'"#]/g, function(s) { return c[s]; } ); } alert( ConvChar('<-"-&-"->-<-\'-#-\'->') );
结果:
<-"-&-"->-<-'-#-'->
在testarea标签中:
<-"-&-"->-<-'-#-'->
如果你只是用长代码改变一个小字符......
答案 6 :(得分:6)
function char_convert() {
var chars = ["©","Û","®","ž","Ü","Ÿ","Ý","$","Þ","%","¡","ß","¢","à","£","á","À","¤","â","Á","¥","ã","Â","¦","ä","Ã","§","å","Ä","¨","æ","Å","©","ç","Æ","ª","è","Ç","«","é","È","¬","ê","É","","ë","Ê","®","ì","Ë","¯","í","Ì","°","î","Í","±","ï","Î","²","ð","Ï","³","ñ","Ð","´","ò","Ñ","µ","ó","Õ","¶","ô","Ö","·","õ","Ø","¸","ö","Ù","¹","÷","Ú","º","ø","Û","»","ù","Ü","@","¼","ú","Ý","½","û","Þ","€","¾","ü","ß","¿","ý","à","‚","À","þ","á","ƒ","Á","ÿ","å","„","Â","æ","…","Ã","ç","†","Ä","è","‡","Å","é","ˆ","Æ","ê","‰","Ç","ë","Š","È","ì","‹","É","í","Œ","Ê","î","Ë","ï","Ž","Ì","ð","Í","ñ","Î","ò","‘","Ï","ó","’","Ð","ô","“","Ñ","õ","”","Ò","ö","•","Ó","ø","–","Ô","ù","—","Õ","ú","˜","Ö","û","™","×","ý","š","Ø","þ","›","Ù","ÿ","œ","Ú"];
var codes = ["©","Û","®","ž","Ü","Ÿ","Ý","$","Þ","%","¡","ß","¢","à","£","á","À","¤","â","Á","¥","ã","Â","¦","ä","Ã","§","å","Ä","¨","æ","Å","©","ç","Æ","ª","è","Ç","«","é","È","¬","ê","É","­","ë","Ê","®","ì","Ë","¯","í","Ì","°","î","Í","±","ï","Î","²","ð","Ï","³","ñ","Ð","´","ò","Ñ","µ","ó","Õ","¶","ô","Ö","·","õ","Ø","¸","ö","Ù","¹","÷","Ú","º","ø","Û","»","ù","Ü","@","¼","ú","Ý","½","û","Þ","€","¾","ü","ß","¿","ý","à","‚","À","þ","á","ƒ","Á","ÿ","å","„","Â","æ","…","Ã","ç","†","Ä","è","‡","Å","é","ˆ","Æ","ê","‰","Ç","ë","Š","È","ì","‹","É","í","Œ","Ê","î","Ë","ï","Ž","Ì","ð","Í","ñ","Î","ò","‘","Ï","ó","’","Ð","ô","“","Ñ","õ","”","Ò","ö","•","Ó","ø","–","Ô","ù","—","Õ","ú","˜","Ö","û","™","×","ý","š","Ø","þ","›","Ù","ÿ","œ","Ú"];
for(x=0; x<chars.length; x++){
for (i=0; i<arguments.length; i++){
arguments[i].value = arguments[i].value.replace(chars[x], codes[x]);
}
}
}
char_convert(this);
答案 7 :(得分:4)
正如dragon
所提到的那样,最简单的方法是使用jQuery
:
function HtmlEncode(s) {
return $('<div>').text(s).html();
}
function HtmlDecode(s) {
return $('<div>').html(s).text();
}
答案 8 :(得分:3)
解决方法:
var temp = $("div").text("<");
var afterEscape = temp.html(); // afterEscape == "<"
答案 9 :(得分:2)
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230, 8482, 169, 61558, 8226, 61607);
var swapStrings = new Array("--", "--", "'", "'", '"', '"', "*", "...", "™", "©", "•", "•", "•");
var TextCheck = {
doCWBind:function(div){
$(div).bind({
bind:function(){
TextCheck.cleanWord(div);
},
focus:function(){
TextCheck.cleanWord(div);
},
paste:function(){
TextCheck.cleanWord(div);
}
});
},
cleanWord:function(div){
var output = $(div).val();
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g");
output = output.replace(swapper, swapStrings[i]);
}
$(div).val(output);
}
}
我们现在使用的另一个有效。我上面有一个调用脚本而返回转换后的代码。只对小textareas有好处(意思不是完整的文章/博客等...)
对于上方。适用于大多数字符。
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230, 8482, 61558, 8226, 61607,161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 338, 339, 352, 353, 376, 402);
var swapStrings = new Array("--", "--", "'", "'", '"', '"', "*", "...", "™", "•", "•", "•", "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "­", "®", "¯", "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", "Œ", "œ", "Š", "š", "Ÿ", "ƒ");
我创建了一个包含上述功能的javascript文件。 http://www.neotropicsolutions.com/JSChars.zip
包含所有需要的文件。我添加了jQuery 1.4.4。仅仅因为我在其他版本中看到了问题,但还是尝试了它们。
Requires: jQuery & jQuery Impromptu from: http://trentrichardson.com/Impromptu/index.php
1. Word Count
2. Character Conversion
3. Checks to ensure this is not passed: "notsomeverylongstringmissingspaces"
4. Checks to make sure ALL IS NOT ALL UPPERCASE.
5. Strip HTML
// Word Counter
$.getScript('js/characters.js',function(){
$('#adtxt').bind("keyup click blur focus change paste",
function(event){
TextCheck.wordCount(30, "#adtxt", "#adtxt_count", event);
});
$('#adtxt').blur(
function(event){
TextCheck.check_length('#adtxt'); // unsures properly spaces-not one long word
TextCheck.doCWBind('#adtxt');// char conversion
});
TextCheck.wordCount(30, "#adtxt", "#adtxt_count", false);
});
//HTML
<textarea name="adtxt" id="adtxt" rows="10" cols="70" class="wordCount"></textarea>
<div id="adtxt_count" class="clear"></div>
// Just Character Conversions:
TextCheck.doCWBind('#myfield');
// Run through form fields in a form for case checking.
// Alerts user when field is blur'd.
var labels = new Array("Brief Description","Website URL","Contact Name","Website","Email","Linkback URL");
var checking = new Array("descr","title","fname","website","email","linkback");
TextCheck.check_it(checking,labels);
// Extra security to check again, make sure form is not submitted
var pass = TextCheck.validate(checking,labels);
if(pass){
//do form actions
}
//Strip HTML
<textarea name="adtxt" id="adtxt" rows="10" cols="70" onblur="TextCheck.stripHTML(this);"></textarea>
答案 10 :(得分:2)
对于想要在字符串内解码一个整数字符代码(如&#xxx;
)的人,请使用以下功能:
function decodeHtmlCharCodes(str) {
return str.replace(/(&#(\d+);)/g, function(match, capture, charCode) {
return String.fromCharCode(charCode);
});
}
// Will output "The show that gained int’l reputation’!"
console.log(decodeHtmlCharCodes('The show that gained int’l reputation’!'));
const decodeHtmlCharCodes = str =>
str.replace(/(&#(\d+);)/g, (match, capture, charCode) =>
String.fromCharCode(charCode));
// Will output "The show that gained int’l reputation’!"
console.log(decodeHtmlCharCodes('The show that gained int’l reputation’!'));
答案 11 :(得分:2)
如果您需要all standardized named character references,unicode和ambiguous ampersands的支持,he库是我所知道的唯一100%可靠的解决方案!
he.encode('foo © bar ≠ baz qux');
// Output : 'foo © bar ≠ baz 𝌆 qux'
he.decode('foo © bar ≠ baz 𝌆 qux');
// Output : 'foo © bar ≠ baz qux'
答案 12 :(得分:2)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>html</title>
<script>
$(function() {
document.getElementById('test').innerHTML = "&";
});
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
您可以使用上面的代码将特殊字符转换为html。
答案 13 :(得分:1)
以下是我使用的一些方法而不需要Jquery:
您可以对字符串中的每个字符进行编码:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
或者只是针对主要的安全编码字符来担心(&amp;,inebreaks,&lt;,&gt;,“和”),例如:
function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}
test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');
/*************
* \x26 is &ersand (it has to be first),
* \x0A is newline,
*************/
<textarea id=test rows="9" cols="55">www.WHAK.com</textarea>
答案 14 :(得分:1)
这是一个很好的图书馆,我发现在这种情况下非常有用。
https://github.com/mathiasbynens/he
据其作者说:
它支持所有标准化的命名字符引用,按照HTML, 处理模糊的&符号和其他边缘情况就像浏览器一样 会有一个广泛的测试套件,并且 - 与其他许多相反 JavaScript解决方案 - 他处理星形Unicode符号就好了
答案 15 :(得分:0)
您可以通过替换函数.text()来修复它 到.html()。它对我有用。
答案 16 :(得分:0)
function escape (text)
{
return text.replace(/[<>\&\"\']/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
});
}
alert(escape("<>&'\""));
答案 17 :(得分:0)
以下是在JS中编码xml转义字符的简单函数
Encoder.htmlEncode(unsafeText);
答案 18 :(得分:0)
我们可以使用javascript DOMParser
进行特殊字符转换。
const parser = new DOMParser();
const convertedValue = (parser.parseFromString("' & ' < >", "application/xml").body.innerText;
答案 19 :(得分:0)
这不会直接回答您的问题,但如果您使用innerHTML
来编写元素中的文本并遇到编码问题,请使用textContent
,即:
var s = "Foo 'bar' baz <qux>";
var element = document.getElementById('foo');
element.textContent = s;
// <div id="foo">Foo 'bar' baz <qux></div>
答案 20 :(得分:-1)
<html>
<body>
<script type="text/javascript">
var str= "&\"'<>";
alert('B4 Change:\n' + str);
str= str.replace(/\&/g,'&');
str= str.replace(/</g,'<');
str= str.replace(/>/g,'>');
str= str.replace(/\"/g,'"');
str= str.replace(/\'/g,''');
alert('After change:\n' + str);
</script>
</body>
</html>
用它来测试:http://www.w3schools.com/js/tryit.asp?filename=tryjs_text
答案 21 :(得分:-1)
请参阅JavaScript htmlentities http://phpjs.org/functions/htmlentities:425
答案 22 :(得分:-1)
是的,但如果您需要将结果字符串插入某个地方而不将其转换回来,则需要执行以下操作:
str.replace(/'/g,"&amp;#39;"); // and so on
答案 23 :(得分:-3)
public static string HtmlEncode (string text)
{
string result;
using (StringWriter sw = new StringWriter())
{
var x = new HtmlTextWriter(sw);
x.WriteEncodedText(text);
result = sw.ToString();
}
return result;
}
答案 24 :(得分:-4)