0

I have a string in JavaScript that contains a quote mark - for example, Don't click this checkbox or He said "hi". I am trying to find a checkbox that has the exact same value.

For my first example, I have the HTML:

<input type="checkbox" value="Don\'t click this checkbox">

And my variable q has the string Don't click this checkbox in it. To try and query for this checkbox, I have the following code. Where am I going wrong?

q = q.replace("'", "\'").replace("\"", "\\"");
var $checkbox = $("input:checkbox[value='" + q + "']");
theeggman85
  • 1,745
  • 6
  • 23
  • 36
  • What do you get when you add the line `console.log($checkbox)` at the end? – karancan Mar 17 '13 at 21:52
  • Why does the value need the \? Can't you just set the value to `Don't click this checkbox`? – scott.korin Mar 17 '13 at 21:58
  • [This related question](http://stackoverflow.com/questions/739695/jquery-selector-value-escaping) might be helpful. I got it working using `var q = "Don\\\\'t click this checkbox";` if that helps. – Andrew Whitaker Mar 17 '13 at 22:01

1 Answers1

0

The problem is with the second replace function: .replace("\"", "\\"");

Since you have a double quote in a string delimted by double quotes, you have to escape the inside double quote. Or, make it easy on yourself and use single quotes:

q = q.replace("'", "\'").replace('"', '\"');
scott.korin
  • 2,537
  • 2
  • 23
  • 36
  • I was thinking about this. My main problem is that I tested this code with just the first replacement of single quotes, and it still didn't work, so something was already going wrong with just that. Do I need more backslashes like Andrew suggested? – theeggman85 Mar 18 '13 at 00:58