In my javascript, how can I fix this encoding issue between "\u0026", "&" and "&"?

1.9k views Asked by At

I have an asp.net-mvc website and I have the following code in one of my views:

var teams = <%= new JavaScriptSerializer().Serialize(Model.Names) %>;

Model.Names is a string array and one of the names, a team has a name "Joe & Bob" and it shows up in the html as:

 "Joe \u0026 Bob"

even though it displays as "Joe & Bob" in the browser

The issue is that I have another line of code that tries to do a compare against "Joe & Bob" and it can't find it. When i looked into it the code on why its failing its simply spitting out a variable like this

 "<%= Model.Name %>",

and in the browser source I see

"Joe & Bob" 

(instead of Joe \u0026 Bob)

I tried doing this

   <%=Html.Encode(Model.Name); %>

so I can do a proper comparison but I got:

 Joe &amp; Bob

instead of Joe \u0026 Bob

I wanted to get some advice for the cleanest way to get the same exact string in the browser source so I could do a proper comparison.

1

There are 1 answers

4
StriplingWarrior On BEST ANSWER

In JavaScript "\u0026" is totally equivalent to "&", so if you were doing a javascript comparison this would work fine:

console.log("Joe \u0026 Bob" == "Joe & Bob"); // true

But if you want to represent this string in text, you definitely want it to be HTML-encoded into &amp; instead.

<span class="name"><%=Html.Encode(Model.Name)%></name>

If you do this, then the text value of the DOM element should still be "Joe & Bob" as far as JavaScript is concerned:

console.log($('.name').text()); // "Joe & Bob"
console.log($('.name').text() == "Joe & Bob"); // true
console.log($('.name').text() == "Joe \u0026 Bob"); // true