Using a variable name for the string.replace() regexp

  • Thread starter X l e c t r i c
  • Start date
X

X l e c t r i c

Here:

http://bigbangfodder.fileave.com/res/sandr.html

I'm trying to use string.replace() for a basic search and replace form
using textarea values as the regexp and replacement values for
string.replace().

When I tried to use the textarea variable name for regexp it didn't work
as I thought it would. For example:

string.replace(/variablename/, replacementvariablename);

This actually searched for variablename instead of the value it
represents. Which actually makes sense. What I did to solve the problem
was this:

var e_v = eval('/' + variablename + '/' + g_b + c_s);

where g_b and c_s are variable names for global and sensitivity
depending upon whether or not checkboxes are checked.

Then I follow that with:

t_ai.value = t_ai.value.replace(e_v, t_ar);

t_ai is the variable name for the textarea that holds the text that's
being searched and t_ar is the variable name for the replacement
textarea value.

Is there a way that I can accomplish this without using eval() ?

The text in the textareas and the "Clear Values" button are there as a
convenience for anyone who takes a look to help me, and won't be there
when I'm finished.

Art
 
R

RobG

Here:

http://bigbangfodder.fileave.com/res/sandr.html

I'm trying to use string.replace() for a basic search and replace form
using textarea values as the regexp and replacement values for
string.replace().

When I tried to use the textarea variable name for regexp it didn't work
as I thought it would. For example:

string.replace(/variablename/, replacementvariablename);

This actually searched for variablename instead of the value it
represents. Which actually makes sense. What I did to solve the problem
was this:

var e_v = eval('/' + variablename + '/' + g_b + c_s);

Use RegExp as a constructor:

var e_v = new RegExp(variablename, g_b + c_s);
 
X

X l e c t r i c

RobG wrote:

Use RegExp as a constructor:

var e_v = new RegExp(variablename, g_b + c_s);

That's outstanding Rob.

I had tried different versions of the RegExp constructor but they
included the slashes ( / ) and various combinations of quotes, and they
obviously didn't work.

Thank you very much.

Art
 

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,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top