简体   繁体   中英

String is treated differently when extracted from DOM

I am facing a very weird problem with Javascript. When I extract text from DOM and try to decode HTML entities, it's not working. However, when I assign the value directly in the code, it's working just fine.

I just don't get why the string is treated differently in both cases. I have tested in FireFox and Chrome and both produce the same result.

Update : The correct output should be %7B (after decoding the string). That means that when I assign the value directly to the variable it's working correctly, but when extracted from DOM, it's not. How can I extract the text from DOM and decode it so it produces "%7B" ?

DEMO : jsFiddle

HTML :

<div class="myclass">\u00257B</div>

Javascript Code:

    $(document).ready(function(){

    //Extracting the text from DOM
   var myText = $(".myclass").html();
    //decoding HTML entities
   var decodedText = $("<div />").html(myText).text();
    //alerting the decoded text
    alert(decodedText); // output: \u00257B

    //assigning the value directly to the variable
   var myText2 = "\u00257B";
    //decoding HTML entities
   var decodedText2 = $("<div />").html(myText2).text();
    //alerting decoded text
    alert(decodedText2); // output: %7B

});

The reason myText2 produces a different result is because the backslash in string literals is an escape character.

to escape a backslash, simply use it twice:

myText2 = "\\u00257b";

Here is a some further information about escape characters in JavaScript


EDIT

There's probably a better way, but this will work: (eval is generally frowned upon and has security implications if the value from your text is uncontrolled input)

myText = eval("\"" + decodedText + "\"")

I think this is because when you extract the string from the dom the "\\u\u0026quot; is escaped.

If you do var myText2 = "\\\%7B"; you'll get the same result

http://jsfiddle.net/9n6t5qxr/1/

if you do console.log('\%') it prints % , which is why you are seeing %7B

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