How to Escape a Single Quote ( ' ) in JavaScript

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

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

Escape single quote in JavaScript

Use jQuery to set the value;

function makeTitleEditable($titleContainer){
$titleContainer.replaceWith(
$("<input id='poll_title' name='poll[title]' type='text'>").val($titleContainer.text())
);
}

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';
});

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.

Escape single quotes in title

You can use double quote:

myTitle = "abc '' def";
document.write('<img title="' + myTitle + '" src="http://www.example.com/image.png" />');

or escape the quote:

myTitle = "abc '' def";
document.write("<img title='" + myTitle.replace(/'/g, ''') + "' src='http://www.example.com/image.png' />");


Related Topics



Leave a reply



Submit