question about match or replace

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wesley1970
    New Member
    • Nov 2007
    • 15

    question about match or replace

    in php we have

    [PHP]
    <?php>
    $pattern[0]='/a/i';
    $pattern[1]='/b/i';
    $replacement[0]='';
    $replacement[1]='';
    $var = 'Watbe';
    echo preg_replace($p attern, $replacement, $var);
    ?>[/PHP]

    using pattern array to replace two match at the same time.


    Under is what i know in javascript
    [HTML]<script>
    var str="aacc";
    var rs=str.replace(/a/i,"0");
    </script>[/HTML]

    Is there any patterns array for us to use like the php one???
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    I'm afraid, there isn't anything like that.

    Instead, you may do it like this:[CODE=javascript]string.replace( srch[0], rplc[0]).replace(srch[1], rplc[1]);//and so on... [/CODE]

    Or you can create a function similar to preg_replace of PHP which will iterate for each string in the array and repeat the replace() function accordingly.

    Comment

    • rnd me
      Recognized Expert Contributor
      • Jun 2007
      • 427

      #3
      Code:
      String.prototype.replaceAll = function (r) {
          O = this;
          for (z = 0; z < r.length; z++) {
              tre = new RegExp(r[z][0], "gm");
              O = O.replace(tre, r[z][1]);
          }
          return O;
      }
      
      replacements = [
         ["hello","goodbye"], 
         ["world", "earth"]
      ]; //orig  //replacement
      
      alert("hello world".replaceAll(replacements ));  //shows "goodbye earth"

      Comment

      Working...