开发者

Data parsed from an XML file renders %22% for " and %27% for '...how do I fix this?

开发者 https://www.devze.com 2023-03-31 10:52 出处:网络
I am parsing data from an XML file and the XML has the character \' encoded as %27% and the character \" as %22%. Those characters render in my HTML, so I end up with data like this:

I am parsing data from an XML file and the XML has the character ' encoded as %27% and the character " as %22%. Those characters render in my HTML, so I end up with data like this:

Pike%27%s Peak

o开发者_Go百科r

this is my %22%Quote%22%

I attempted to perform a string.replace(), but to no avail. I am such a newbie when it comes to parsing XML with javascript. I'm sure my code is way off, but that's why I'm posting this quest...can anyone help me out? Here's the code for my attempted string.replace():

function xmlencode(string) {
return string.replace(/'%27'/g,'\'').replace(/'%22'/g,'\"');

}

Your feedback is much appreciated.

Thanks, Carlos


That's some proprietary encoding, that's nothing that is usually used in an XML file. Because of that, there is no standard way of decoding it.

You have some extra apostrophes in your function that keeps it from working:

function decode(string) {
  return string.replace(/%27%/g,"'").replace(/%22%/g,'"');
}

You can parse the hex code between the percent signs to get a function that works for any such entity:

function decode(string) {
  return string.replace(/%[\da-f]{2}%/gi,function(m) {
    return String.fromCharCode(parseInt(m.substr(1,2), 16));
  });
}

Example:

alert(decode("%49%%74%%20%%77%%6f%%72%%6b%%73%%21%"));
0

精彩评论

暂无评论...
验证码 换一张
取 消