Escape Quotes in JavaScript

Escape quotes in JavaScript

You need to escape the string you are writing out into DoEdit to scrub out the double-quote characters. They are causing the onclick HTML attribute to close prematurely.

Using the JavaScript escape character, \, isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation, ".

How do I escape a single quote ( ' ) in JavaScript?

You should always consider what the browser will see by the end. In this case, it will see this:

<img src='something' onmouseover='change(' ex1')' />

In other words, the "onmouseover" attribute is just change(, and there's another "attribute" called ex1')' with no value.

The truth is, HTML does not use \ for an escape character. But it does recognise " and ' as escaped quote and apostrophe, respectively.

Armed with this knowledge, use this:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change("ex1")' />";

... That being said, you could just use JavaScript quotes:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";

Function to escape quotes in JavaScript

query_str = query_str.replace(/"/g, '\\\"');

..will result in; " to \"

OR

query_str = query_str.replace(/"/g, '\\\\\"');

..will result in; " to \\", which will make a printed quotation still be escaped to \".

This code;

var test = 'asdasd " asd a "';

console.log(test.replace(/"/g, '\\\"'));
console.log(test.replace(/"/g, '\\\\\"'));

..outputs;

asdasd \" asd a \"
asdasd \\" asd a \\"

You might adjust the replacement based on how your final interpreter reads the string and prints it out.

How to escape all single and double quotes in JavaScript

You will need to use regular expression for this,

st.replace(/"/g, '\\"');

Check out more on regular expressions here.

Escaping single quotes in JavaScript string for JavaScript evaluation

The thing is that .replace() does not modify the string itself, so you should write something like:

strInputString = strInputString.replace(...

It also seems like you're not doing character escaping correctly. The following worked for me:

strInputString = strInputString.replace(/'/g, "\\'");

How to escape the single quotes and double quotes at the same time

Use a backslash character (\) to escape it:

$("#divId").html('<div onclick="location.href=\"xxx\""');

Here are characters that need to be escaped in javascript strings:

  • Horizontal Tab: \t
  • Vertical Tab: \v
  • Nul char: \0
  • Backspace: \b
  • Form feed: \f
  • Newline: \n
  • Carriage return: \r
  • Single quote: \'
  • Double quote: \"
  • Backslash: \\

As stated in the comments, I would do something different in this case:

$('#divId').html('<div id="foo">');
$('#foo').click(function() {
window.location.href = 'xxx';
});

Don't escape double quotes

There's a github issue about quote format.

The solution given in the link above is to tell uglify to keep the original quote format:

$ echo "console.log(\"foo\",'bar');" | uglifyjs --quotes=1
console.log('foo','bar');

$ echo "console.log(\"foo\",'bar');" | uglifyjs --quotes=2
console.log("foo","bar");

$ echo "console.log(\"foo\",'bar');" | uglifyjs --quotes=3
console.log("foo",'bar');

Or with gulp, give the following as parameter to the uglify.minify() function:

{ output: { quote_style: 3 } }

For your specific problem, as I'm not sure it will keep the unnecessary escape characters (in javascript), a solution would be:

  • remove all single quotes from the javascript by switching everything to double quotes and escape them where necessary
  • uglify the code with the above option
  • do {string: JSON.stringify(code)}

If your javascript code has to have single quotes for some reason, instead you can replace the double quotes in the generated html in the javascript code by " or ".

Note that I don't feel that something like var a = 'abc \" def'; is valid javascript in the first place.

Another thing to look into would be how you include file (it's not mentioned), maybe there's a better way that directly loads the file into a string, on which you can then call JSON.stringify().

Edit

If you use a recent javascript engine, you can also use backquotes (`) in your code and replace double or single quotes by them.

Or, if there's no $ nor backquotes in your javascript code, you can simply do:

{
string: JSON.stringify(`uglified javascript code`)
}

Does Javascript methods auto-escape quotes?

PHP is processed on the server, producing HTML (including embedded javascript in this case). This happens before the HTML is sent to the browser to interpret, including any JS.

You will see if you inspect the generated HTML source, that your second example becomes:

<button onclick="alert('hey a quote ' ');">test</button>

which isn't valid JS syntax.

Your first version works basically because you do not have an extraneous single quote in the code your PHP string is inserted into. The insertion instead produces:

<input type="text" value="hey a quote ' " id="foo" />

which is perfectly fine. And that value is then passed on to the alert call in the JS.



Related Topics



Leave a reply



Submit