Skip to content
Advertisement

Escaping quotes in Javascript variable from Classic ASP

How can I escape quotes using a Classic ASP variable in javascript/jQuery? The ASP variable is taken from a DB. I’m using:

var goala = "<%=(goal_a)%>";

But obviously that appears as

var goala = "<p>testing "quotation" marks</p>";

when the page loads, which breaks the function with unexpected identifier.

edit: I’m using using jQuery not “how can I achieve this using jQuery” sorry wasn’t clear.

Any ideas? Thanks

Answer

You’ve asked how to do this “Using jQuery.” You can’t. By the time jQuery would be involved, the code would already be invalid. You have to fix this server-side.

Classic ASP is unlikely to have anything built-in that will help you solve this in the general case.

Note that you have to handle more than just " characters. To successfully output text to a JavaScript string literal, you’ll have to handle at least the quotes you use (" or '), line breaks, any other control characters, etc.

If you’re using VBScript as your server-side language, you can use Replace to replace the characters you need to replace:

var goala = "<%=Replace(goal_a, """", """")%>";

Again, though, you’ll need to build a list of the things you need to handle and work through it; e.g.

var goala = "<%=Replace(Replace(Replace(goal_a, """", """"), Chr(13), "n"), Chr(10), "r")%>";

…and so on.

If your server-side language is JScript, you can use replace in much the same way:

var goala = "<%=goal_a.replace(/"/g, "\").replace(/r/g, "\r").replace(/n/g, "n")%>";

…and so on. Note the use of regular expressions with the g flag so that you replace all occurrences (if you use a string for the first argument, it just replaces the first match).

Advertisement