String replacement problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • andrewflanders@gmail.com

    String replacement problem

    I have an associative array of keys and values. I want to search a
    string for the existance of keys and replace them with the values in
    the array. The problem is that some of the keys resemble regular
    expressions but they are not so if I build the regular expression with
    a constructor it causes errors saying that the regular expression
    syntax is bad. I got around this problem by skipping the regular
    expression method and passing in the key directly as the first argument
    of replace however this means I lose the ability to pass the /g global
    switch to the replace function so it only replaces once.

    So my question is: is there a way to incorperate a variable into a
    regex without enterpreting the variable as a regex itself or
    alternately is there a way to make the replacement global without using
    a regular expression?

  • RobG

    #2
    Re: String replacement problem

    andrewflanders@ gmail.com wrote:[color=blue]
    > I have an associative array of keys and values. I want to search a
    > string for the existance of keys and replace them with the values in
    > the array. The problem is that some of the keys resemble regular
    > expressions but they are not so if I build the regular expression with
    > a constructor it causes errors saying that the regular expression
    > syntax is bad. I got around this problem by skipping the regular
    > expression method and passing in the key directly as the first argument
    > of replace however this means I lose the ability to pass the /g global
    > switch to the replace function so it only replaces once.
    >
    > So my question is: is there a way to incorperate a variable into a
    > regex without enterpreting the variable as a regex itself or
    > alternately is there a way to make the replacement global without using
    > a regular expression?
    >[/color]

    Do you have a small example to illustrate? Special characters within
    regular expressions can be quoted to remove their special-ness,
    however I'm not sure they are suitable to use as keys for the
    elements of an array.


    --
    Rob

    Comment

    • drWot

      #3
      Re: String replacement problem

      If the string contains something (usually punctuation or control characters)
      that has a special meaning when converted to a regular expression, you have
      to escape it ('.' becomes('\.') before the string is converted.

      This involves looking at each character in each string and testing it
      against a list of suspects [\.\+\=\(\)\&\#\ ^\$\!\?].

      Or you can make each string a new RegExp when you populate the array, and
      make a
      String.prototyp e.convertToRegE xp() method to escape characters based on
      their charCode.

      It would be a little less elegant and a bit more efficient to use string
      methods.

      You can fake a global replace replace by running a regular replace through a
      "while" loop:

      while(str.index Of('badString') !=-1)str=str.repla ce('rString','s omeotherString' ).

      Both methods work, both have pros and cons.








      Comment

      • Lasse Reichstein Nielsen

        #4
        Re: String replacement problem

        andrewflanders@ gmail.com writes:
        [color=blue]
        > I have an associative array of keys and values. I want to search a
        > string for the existance of keys and replace them with the values in
        > the array. The problem is that some of the keys resemble regular
        > expressions[/color]

        Ok, so if you want to use regular expressions for the search, the
        keys need to be escaped (i.e., characters meaningfull to a regular
        expression must be prefixed with a backslash).

        Try this:
        ---
        function replace(string, map) {
        var i=0;
        var keys = [];
        for(var key in map) {
        keys[i++] = key.replace(/([\\.+*?()[{|^$])/g,"\\$1"); // escape chars
        }
        var re = new RegExp(keys.joi n("|"),"g");
        return string.replace( re, function(key) { return map[key]; });
        }
        ---
        (this uses the RegExp way of handling overlapping matches, i.e., if you
        match for /foo|ok/g then "fook" only matches "foo" and not the overlapping
        "ok").
        [color=blue]
        > So my question is: is there a way to incorperate a variable into a
        > regex without enterpreting the variable as a regex itself[/color]

        Yes, escape character meaningfull in a RegExp
        [color=blue]
        > or alternately is there a way to make the replacement global without
        > using a regular expression?[/color]

        Probably, but not easier in any way.

        /L
        --
        Lasse Reichstein Nielsen - lrn@hotpop.com
        DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
        'Faith without judgement merely degrades the spirit divine.'

        Comment

        • Danny

          #5
          Re: String replacement problem


          A string var is a string var, a regexp is a regexp, there's no way to
          confuse a regexp from a string even if the content character wise maybe
          the same, they're different types, so, it isn't it, as for to using a
          variable for a regexp, you use the new RegExp() constructor and escape the
          reserved chars if any:

          var duck='\\w+(\\bf lying\\b)?'; var myregexp=new
          RegExp(duck+'BO LOGNE\\s*$','gi ');

          If the argument is coming from a form input field, those use
          text/plain and any reserved chars are escaped by default.

          Danny

          On Fri, 17 Jun 2005 17:02:24 -0700, <andrewflanders @gmail.com> wrote:
          [color=blue]
          > I have an associative array of keys and values. I want to search a
          > string for the existance of keys and replace them with the values in
          > the array. The problem is that some of the keys resemble regular
          > expressions but they are not so if I build the regular expression with
          > a constructor it causes errors saying that the regular expression
          > syntax is bad. I got around this problem by skipping the regular
          > expression method and passing in the key directly as the first argument
          > of replace however this means I lose the ability to pass the /g global
          > switch to the replace function so it only replaces once.
          >
          > So my question is: is there a way to incorperate a variable into a
          > regex without enterpreting the variable as a regex itself or
          > alternately is there a way to make the replacement global without using
          > a regular expression?
          >[/color]



          --
          Using Opera's revolutionary e-mail client: http://www.opera.com/mail/

          Comment

          Working...