[英]How to output Javascript string with character encoding
所以-我在javascript liks中有一个字符串,所以:
var foo = "Hello™";
我需要以HTML格式(通过JS)打印出来,所以它看起来像这样:
你好™
听起来很简单,但是我显然缺少了一些东西,因为我还没有找到简单的解决方案。
编辑-这是更多代码:
var label = document.createElement('label');
var foo = selectData.options[i][1]; // this is "Hello&trade";
label.innerHTML = foo;
container.appendChild( label );
只需将其附加到innerHTML
属性中即可。 innerHTML
将对给定的输入进行html编码,然后将其附加到节点。
var foo = "Hello™"; document.getElementById('label').innerHTML = foo;
<label id="label"></label>
首先将'&trade'分开,并在if语句中进行检查,然后将hexcode的等效值'u2122'赋予var,然后其余代码即可完成工作。
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
String.prototype.hexDecode = function(){
var j;
var hexes = this.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
var str = "\u2122";
var newStr = (str.hexEncode().hexDecode());
var foo = "Hello" + newStr;
console.log(foo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.