Javascript regular expression: replace()


<!-- Replace all , with . -->

<input type="button" value="Match1" onclick="javascript:demo('Hello Jim, Thank you Jim,');return false;" />
&nbsp;&nbsp;&nbsp;
<input type="button" value="Match2" onclick="javascript:demo('Hello Jack,');return false;" />

<script type="text/javascript" language="JavaScript">
//<![CDATA[
   function demo(text) {
      var re = /,/g;
      var found = text.replace(re, ".");
      if (found != null) {
         alert(found);
      } else {
         alert("no match");
      }
   }
//]]>
</script>


   


<!-- Replace ../ with / and all paths must start with / -->

<input type="button" value="Match1" onclick="javascript:demo2('../../path/test.gif');return false;" />
   
<input type="button" value="Match2" onclick="javascript:demo2('../test.gif');return false;" />
   
<input type="button" value="Match3" onclick="javascript:demo2('/test.gif');return false;" />
   
<input type="button" value="Match4" onclick="javascript:demo2('test.gif');return false;" />


<script type="text/javascript" language="JavaScript">
//<![CDATA[
   function demo2(text) {
      var re1 = /(\.\.\/)+/g;
      var found1 = text.replace(re1, "/");
      var re2 = /^(\w)/gi;
      var found2 = found1.replace(re2, "/$1");
      if (found2 != null) {
         alert(found2);
      } else {
         alert("no match");
      }
   }
//]]>
</script>

           


<!-- Replace http://www.mobilefish.com/ with / -->

<input type="button" value="Match1" onclick="javascript:demo3('http://www.mobilefish.com/path/test.gif');return false;" />
   
<input type="button" value="Match2" onclick="javascript:demo3('/path/test.gif');return false;" />
   
<input type="button" value="Match3" onclick="javascript:demo3('/test.gif');return false;" />
   
<input type="button" value="Match4" onclick="javascript:demo3('test.gif');return false;" />


<script type="text/javascript" language="JavaScript">
//<![CDATA[
   function demo3(text) {
      var re = /http:\/\/[a-z.]+\//gi;
      var found = text.replace(re, "/");
      if (found != null) {
         alert(found);
      } else {
         alert("no match");
      }
   }
//]]>
</script>