By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,814 Members | 2,162 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,814 IT Pros & Developers. It's quick & easy.

question about match or replace

P: 15
in php we have

[PHP]
<?php>
$pattern[0]='/a/i';
$pattern[1]='/b/i';
$replacement[0]='';
$replacement[1]='';
$var = 'Watbe';
echo preg_replace($pattern, $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???
Jul 9 '08 #1
Share this Question
Share on Google+
2 Replies


hsriat
Expert 100+
P: 1,654
I'm afraid, there isn't anything like that.

Instead, you may do it like this:
Expand|Select|Wrap|Line Numbers
  1. string.replace(srch[0], rplc[0]).replace(srch[1], rplc[1]);//and so on... 
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.
Jul 9 '08 #2

rnd me
Expert 100+
P: 427
Expand|Select|Wrap|Line Numbers
  1. String.prototype.replaceAll = function (r) {
  2.     O = this;
  3.     for (z = 0; z < r.length; z++) {
  4.         tre = new RegExp(r[z][0], "gm");
  5.         O = O.replace(tre, r[z][1]);
  6.     }
  7.     return O;
  8. }
  9.  
  10. replacements = [
  11.    ["hello","goodbye"], 
  12.    ["world", "earth"]
  13. ]; //orig  //replacement
  14.  
  15. alert("hello world".replaceAll(replacements ));  //shows "goodbye earth"
  16.  
  17.  
  18.  
Jul 9 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.