12

I have an application, and it is fed some HTML. It then needs to put that HTML into a string. This HTML contains single and double quotes. Is it possible, in javascript, to declare a string with information inside of it, that does not use single or double quotes?

I guess if it is not possible, does anyone know a simple and easy way to escape these quotes so I can put it in a string? Keep in mind, part of this string will be JavaScript that I will later need to execute.

swickblade
  • 4,506
  • 5
  • 21
  • 24
  • Well, i think you need to split it in anyway you could try something like this: var myString = "She's " + '"amazing!"'. does it helps? – Hector Sanchez Jul 08 '11 at 18:21

4 Answers4

10

You need to escape the quotation characters with \:

var someString = 'escape all the quotation marks \"\'';
digitalbath
  • 7,008
  • 2
  • 17
  • 15
4

Is it possible, in javascript, to declare a string with information inside of it, that does not use single or double quotes?

No. JavaScript string literals are delimited with either single quotes or double quotes. Those are the only choices.

does anyone know a simple and easy way to escape these quotes so I can put it in a string?

Do you mean in a string literal?

var str = "var foo=\"bar\"; function say(it) { alert('It is: ' + it); say(foo);";

Or programmatically?

str = str.replace(/"/g, '\\"');
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
2

An easy way to escape the quotes is to use the javascript escape function.

http://www.w3schools.com/jsref/jsref_escape.asp

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • [Consider linking to a more reliable source than w3schools](http://w3fools.com/), such as MDN: https://developer.mozilla.org/en/DOM/window.escape – Matt Ball Jul 08 '11 at 22:19
1

Use the escape function to replace special characters (including single and double quotes). You can then use the unescape function to return the string to it's normal state later if necessary.

For example:

var data = 'hello my name is "James"';
alert(escape(data)); //Outputs: hello%20my%20name%20is%20%22James%22
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • this doesn't answer the question - he's asking how to escape quotation characters so that he can create a string literal. – digitalbath Jul 08 '11 at 20:38
  • @digitalbath - I read the question as more like "I have some data (perhaps the response from an AJAX request) that I need to escape before I can use it", in which case this would be fine. – James Allardice Jul 08 '11 at 20:39