By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,481 Members | 1,199 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,481 IT Pros & Developers. It's quick & easy.

How to escape a quote in a string?

P: n/a
Hi,

I've tried different things, but still can't find how to escape a
single quote in a string:

mystring = '\'stuff\''
var input = new RegExp(mystring,"gi");

ie. how to copy 'stuff' including its native single quotes into the
mystring regex?

Thank you
JD.
Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Jane Doe <ja******@acme.com> writes:
Hi,

I've tried different things, but still can't find how to escape a
single quote in a string:

mystring = '\'stuff\''
That looks correct. Put a "var" in front and a ";" behind, and I can't
find anything to complain about (and those shouldn't change anything
in this exampel).

You could just write
var mystring = "'stuff'";
var input = new RegExp(mystring,"gi");
Let me try:
var mystring = '\'stuff\'';
var re = RegExp(mystring,"gi");
if (re.test("asgasgag'stuff'asfasf")) { alert ("ok");}
if (re.test("asgasgagstuffasfasf")) { alert ("bad");}

This only alerts "ok".
ie. how to copy 'stuff' including its native single quotes into the
mystring regex?


The way you do it looks fine to me.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2

P: n/a
Jane Doe wrote:
Hi,

I've tried different things, but still can't find how to escape a
single quote in a string:

mystring = '\'stuff\''
var input = new RegExp(mystring,"gi");

ie. how to copy 'stuff' including its native single quotes into the
mystring regex?

Thank you
JD.


What you have there should work fine:

var mystring = '\'stuff\'';
var re = new RegExp(mystring, "gi");
alert("'stuff'".replace(mystring, "'newstuff'"));

alerts 'newstuff' in IE6SP1, Netscape 4 and Mozilla.

--
| Grant Wagner <gw*****@agricoreunited.com>

* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/...ce/frames.html

* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/a...ence_entry.asp

* Netscape 6/7 DOM Reference available at:
* http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 7 / Mozilla
* http://www.mozilla.org/docs/web-deve...upgrade_2.html
Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.