user2782752
user2782752

Reputation: 11

How to write double quotes in Javascript

I have this javscript code for creating a xml. Wondering where from a backslash appears when the resulting string is loaded in xml editor or the browser

var i = 0;
var id = 'polyStyID_'+ i;
var kmlStyle =   '<Style id="'+ id +'">';

alert(kmlStyle) gives:<Style id="polyStyID_0">, which is what I want.

But the same string in the browser or xml editor shows a backslash as below

<Style id=\"polyStyID_0\">

What can i do in the Javascript code so that backslash does not appear in the browser?

Thanks for help. BS

Upvotes: 1

Views: 170

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 187134

But the same string in the browser or xml editor shows a backslash

You have the string you want. Some places that string gets previewed may insert backslashes. This is because it's trying to tell that those quotes do not actually terminate the string, and are instead content.

The reason alert works like you expect is because alter doesn't show a representation of the string, it shows the string data, which is correct.

Don't worry about the backslashes, they aren't really there. If you write the string out somewhere the backslashes will not be there, as the alert shows.

More proof here, showing you can write this string to the the value of a form field without backslashes.

Upvotes: 1

Praveen
Praveen

Reputation: 56509

\It is the escape character in JS. Hence it is shown.

Also you should consider using .setAttribute("id", "uniqueIdentifier");

Upvotes: 1

Related Questions