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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • X l e c t r i c

    #1

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

    Here:



    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/, replacementvari ablename);

    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.repl ace(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

  • RobG

    #2
    Re: Using a variable name for the string.replace( ) regexp

    On Mar 2, 12:51 pm, Xlect...@webtv. net (X l e c t r i c) wrote:
    Here:
    >

    >
    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/, replacementvari ablename);
    >
    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(variable name, g_b + c_s);


    --
    Rob

    Comment

    • X l e c t r i c

      #3
      Re: Using a variable name for the string.replace( ) regexp

      RobG wrote:

      Use RegExp as a constructor:

      var e_v = new RegExp(variable name, 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

      Comment

      Working...