开发者

JQuery escape apostrophes and double apostrophes?

I want to use JQ to print to a div on my page. The string I want to print with contains HTML including apostrophes and double apostrophes.

Is there a plugin or function to escape this so that the string doesnt break the js variable? There may be the case that I can't escape all of the apostrophes and double apostrophes in the incoming data using a backslash, so I'm looking for a function that can do it.

EG;

var replacement = 'This content has an apostrophe ' and a double apostrophe "';

$("#overwrite").text(replace开发者_如何学Pythonment);

TIA


If you wanted to type out a string that is assigned to a variable like in your example above, then just escape it yourself.

For example, if I know my data will have apostrophes, then I wrap it in quotes (what you are calling double apostrophes) and use the HTML shortcut for quotes " or you can use a backslash to escape the quote \". Either way works. So your example above would become:

var replacement = "This content has an apostrophe ' and a double apostrophe "";

If the user is typing in the string or you are getting data from a feed, then it would be best to use the javascript replace function to make sure the quotes are escaped, like this:

var text = $("input").val().replace(/\"/g,""");


There is no need to escape incoming data, as it is already a string.

The only reason you need to escape apostrophes and double apostrophes in JavaScript source is due to the fact the JavaScript engine has to determine where the string starts and ends.

For instance, assuming you have a div#source containing the text "Hi there, what's up!", it is perfectly safe to do $("#overwrite").text($("#source").text()).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜