`

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>
 

 

 

分享到:
评论

相关推荐

    js中字符替换函数String.replace()使用技巧

    在JavaScript中,`String.prototype.replace()` 是一个非常重要的字符串方法,用于在字符串中查找匹配的模式(可以是正则表达式或子字符串)并替换它们。这个方法的使用技巧广泛,能够实现各种复杂的字符串处理需求...

    Javascript String.replace的妙用

    字符替换是一个非常重要的功能,javascript 中有一个 String.replace( ),但是此方法有很多不为新手所知的妙用,如果用的好了,可以为您节省很多宝贵时间,还等什么?马上进来看看吧!

    javascript笔记 String类replace函数的一些事.docx

    ### JavaScript中的`String.prototype.replace`方法详解 #### 一、`replace`方法的基本用法 在JavaScript中,`String.prototype.replace`是一个非常重要的方法,用于替换字符串中的某些部分。其基本语法如下: ``...

    关于JS字符串函数String.replace()

    JS字符串函数String.replace()是JavaScript中一个非常实用的字符串操作方法,它允许开发者针对字符串中的文本进行替换。这个函数对于文本处理非常重要,因为它可以应用正则表达式来实现复杂的模式匹配和替换逻辑。 ...

    Js中去掉空格经典代码

    为了方便使用,这里采用扩展JavaScript原生`String`对象的方法实现,即通过扩展`String.prototype`来实现这些功能: ```javascript String.prototype.Trim = function () { return this.replace(/(^\s*)|(\s*$)/g,...

    JavaScript中String.prototype用法实例

    本文实例讲述了JavaScript中String.prototype用法。分享给大家供大家参考。具体如下: // 返回字符的长度,一个中文算2个 String.prototype.ChineseLength=function() { return this.replace(/[^\x00-\xff]/g,"**...

    Js里面给String添加trim()方法,实现去掉字符串两边空格

    原生的JavaScript自ECMAScript5标准引入后,就已经提供了`String.trim()`方法来去除字符串首尾的空白字符,这为开发者带来了极大的便利。然而,在此之前,或者在某些特定环境下(如旧版本的浏览器),`String.trim()...

    string-replace-async:异步String.prototype.replace()

    字符串替换异步知道如何等待的“ string” .replace()函数安装$ npm install string-replace-async用法let replaceAsync = require ( "string-replace-async" ) ;await replaceAsync ( "#rebeccapurple" , / # ( \...

    JavaScript.and.Ajax.for.the.Web.6th.EditionI

    JavaScript.and.Ajax.for.the.Web.6th.Edition English version.

    JavaScript中String.match()方法的使用详解

    &lt;title&gt;JavaScript String.match() Method &lt;script type="text/javascript"&gt; var str = "For more information, see Chapter *.*.*.*"; var re = /(chapter\d+(\.\d)*)/i; var found = str.match(re); document....

    JavaScript String.replace函数参数实例说明

    Email:longsu2010 at yeah dot net js String的replace函数的函数签名如下: replace(match/* 字符串OR正则表达式 */, replacement/* 字符串OR函数 */) 作用是将源自符串中的match替换为replacement并返回替换后的...

    为javascript添加String.Format方法

    然而,JavaScript原生并不提供像C#或Java那样的`String.Format`方法,这使得在需要格式化字符串时,开发者通常需要使用加号(+)或者模板字符串(ES6引入的新特性)来组合字符串和变量。这在处理复杂格式化需求时...

    Javascript.Object.Oriented.Programming.pdf

    loops, and best practices on using types and data structures, as well as the coding style and recommended code organization patterns in JavaScript. The book will also teach you how to use arrays and ...

    JS写的仿C#的String.Format函数

    string message = String.Format("My name is {0} and I am {1} years old.", name, age); ``` 在这个例子中,`{0}`和`{1}`被`name`和`age`的值替换,生成的字符串是"My name is John and I am 30 years old."。 ...

Global site tag (gtag.js) - Google Analytics