简体   繁体   中英

Proper way of encoding a java script string

I have used escape function of java script to encode a java script string. But the result appears to be weird one which consists of the following characters:

%3CBitte%20w%E4hlen%3E

…for the string:

Bitte wählen

…which is a German sentence. I need the output as Bitte wählen .

The following code may help you understand clearly

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

It's not really clear what you mean.

To escape any character in JavaScript, read up on JavaScript character escape sequences , or just use mothereff.in/js-escapes . That page tells you that in JavaScript, 'Bitte wählen' can be written as 'Bitte w\\xe4hlen' or even '\\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>

(Code taken from here )

Demo: http://jsfiddle.net/karim79/nnRpn/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM