Javascript: How to convert userinput *string* to *regex* for use in replace

P

Phil

I wonder how one converts a string into a real regex...

if I try something like:

var sRegex=userinput.value
var sResult = sSomestring.replace(sRegex, "xxx");

the sRegex is interpreted as a string and not as a real /regex/

How can I change this so the user can enter a regex and have it interpreted?

I guess this requires some kind of cast but to what kind of objectype?
 
J

Jim Ley

I wonder how one converts a string into a real regex...

if I try something like:

var sRegex=userinput.value
var sResult = sSomestring.replace(sRegex, "xxx");

the sRegex is interpreted as a string and not as a real /regex/

new RegExp(sRegex)

Jim.
 
M

Martin Honnen

Phil said:
I wonder how one converts a string into a real regex...

if I try something like:

var sRegex=userinput.value

var rexExp = new RegExp(userinput.value)
 

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

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top