java脚本字符串的正确编码方式

Proper way of encoding a java script string

本文关键字:编码 方式 脚本 字符串 java      更新时间:2023-09-26

我使用了java脚本的转义函数来编码java脚本字符串。但结果似乎很奇怪,它由以下字符组成:

%3CBitte%20w%E4hlen%3E

…对于字符串:

Bitte wählen

…这是一个德语句子。我需要输出为Bitte wählen

以下代码可以帮助您清楚地理解

var temp = escape(String(<Bitte wählen>));

你的意思并不清楚。

要对JavaScript中的任何字符进行转义,请阅读JavaScript字符转义序列,或者只使用mothereff.in/js-escapes。该页面告诉您,在JavaScript中,'Bitte wählen'可以写成'Bitte w'xe4hlen',甚至''x42'x69'x74'x74'x65'x20'x77'xe4'x68'x6c'x65'x6e'

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

alert(URLDecode("%3CBitte%20w%E4hlen%3E"));​ // <Bitte wählen>

(代码取自此处)

演示:http://jsfiddle.net/karim79/nnRpn/