How can I accommodate a string with both single and double quotes inside of it in Javascript

寵の児 提交于 2019-12-28 06:21:14

问题


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?

Thanks, and 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.

Thanks!


回答1:


You need to escape the quotation characters with \:

var someString = 'escape all the quotation marks \"\'';



回答2:


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, '\\"');



回答3:


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

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




回答4:


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


来源:https://stackoverflow.com/questions/6628639/how-can-i-accommodate-a-string-with-both-single-and-double-quotes-inside-of-it-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!