How to escape a quote in a string?

J

Jane Doe

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.
 
L

Lasse Reichstein Nielsen

Jane Doe said:
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
 
G

Grant Wagner

Jane said:
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 <[email protected]>

* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/manuals/2000/javascript/1.3/reference/frames.html

* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/author/dhtml/reference/dhtml_reference_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-developer/upgrade_2.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,085
Messages
2,570,597
Members
47,219
Latest member
Geraldine7

Latest Threads

Top