`

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.rar

    javascript-String.rar

    Javascript String.replace的妙用

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

    js 页面刷新location.reload和location.replace的区别小结.docx

    JavaScript 中的 location.reload 和 location.replace 方法的区别 在 JavaScript 中,我们经常使用 location.reload() 和 location.replace() 两个方法来刷新页面或重定向到新的 URL。但是,这两个方法之间有着...

    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()...

    javascript.string.format:java的String.format()的Javascript实现;

    java 的 String.format() 的 Javascript 实现,增加了支持格式化百分比和后缀-SI,如 120M、30K。 将 Formatter.format() 移植到 javascript 的基本开始。 目前依赖 .toLocaleString() 进行命名日期格式。 请参阅...

    JS仿C#的String.Format函数

    在JavaScript中,没有内置的`String.Format`函数,如C#中那样,它提供了一种方便的方式来格式化字符串。然而,由于JavaScript的灵活性,我们可以创建一个类似的函数来实现这一功能。`String.Format`的主要作用是将...

    String.prototype.replaceAll:适用于String.prototype.replaceAll ESnext提案的符合规范的polyfill

    string.prototype.replaceall 用于String.prototype.replaceAll的ES Proposal规范填充程序。 如果不可用或不String.prototype....// replaceAll and replace are the same, when given a global regex to replace as

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

    string.replace(regexp, replacement) 参数: regexp: RegExp对象或者字符串 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 ...

    前端项目-underscore.string.zip

    首先,underscore.string是underscore.js库的一个扩展,它为JavaScript的String对象添加了超过150个实用方法,涵盖了字符串处理的各个方面,如格式化、分割、查找替换、大小写转换等。这个库的设计理念是使字符串...

    [JavaScript权威指南(第6版)].(JavaScript:The.Definitive.Guide).David.Flanagan.文字版.pdf

    - **标题**: "[JavaScript权威指南(第6版)].(JavaScript:The Definitive Guide).David Flanagan.文字版.pdf" - **描述**: "[JavaScript权威指南(第6版)].(JavaScript:The Definitive Guide).David Flanagan.文字版...

    js中关于String对象的replace使用详解.docx

    ### JavaScript中String对象的replace方法使用详解 #### 一、引言 在JavaScript编程中,字符串处理是一项非常常见的任务。`String`对象提供了多种方法来帮助我们高效地处理字符串数据,其中`replace`方法尤其重要...

    Chart 极品web报表控件收集(Flot,AmCharts, Emprise JavaScript Charts...)

    • Emprise JavaScript Charts - Emprise 是一个100% 纯 JavaScript 图表解决方案,并不需要任何 JavaScript 框架. • PlotKit - PlotKit 是一个 图表和图像的Javascript 库. PlotKit 和 MochiKit javascript 库...

Global site tag (gtag.js) - Google Analytics