javascript the string.replace method and its use

string.replace method accept a regexpression as the seperator, also, you can pass some anonymous function which will work on each of the matched method;

 

let's see the example. 

 

 

/**************************************
*@Summary
*  this file demonstrate the use of string.replace method, which can accept some regexpression and an additional function which works on each and every element that is returned by the match  
*
* 
* @Usage:
*   
* compress( "foo=1&foo=2&blah=a&blah=b&foo=3" ) == "foo=1,2,3&blah=a,b"
*
* @TODO:
* some more practical use of the string.replac method call 
*  assert("a b c".replace(/a/, function() { return ""; } ) == " b c", "returning an empty result removes a match");
***************************************/


function compress(data) { 
  var q = [], ret = [];

  // in the anonymouse function, the first argument is the entire match, and followed by each, subsequent capture following.
  data.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) { 
    q[key] = (q[key] ? q[key] + "," : "") + value;
    // why do we need to return a empty string? 
    // the return value of the replace method call will be injected back to the string as replacement. 
    // by returning a empty string, we are clearning the matched values.
    return "";
  });

  for (var key in q)
  {
    ret.push(key + "=" + q[key]); 
  }

  return ret.join("&");
}
 

and below is the code that test the functions above, which also shows you the tricks on how to make use of the return value from the anonymous function. 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="strregex.js" ></script>
    <script type="text/javascript" src="../unit.js"></script>
    <script type="text/javascript">
      window.onload = function () {
        test("test string replace method call", function () {
          assert(compress("foo=1&foo=2&blah=a&blah=b&foo=3") == "foo=1,2,3&blah=a,b", "verity the compression method");
        });
        test("Test string replace method 2", function () {
          assert("a b c".replace(/a/, function () { return ""; }) == " b c", "Returning an empty result removes a match.");
        });
      };
    </script>
    <style> 
      #results li.pass { color: Green }
      #results li.fail { color: Red}
    </style>
</head>
<body>
<ul id="results" />
</body>
</html>
 

 

 

你可能感兴趣的:(JavaScript)