字符串的替换函数replace平常使用的频率非常高,format函数通常用来填补占位符。下面简单总结一下这两个函数的用法。

一、String.replace的两种用法

  replace的用法如:replace(regexp, string|fn);第一个参数都是正则表达式,第二个参数可以是要替换的字符串,也可以是带返回值的函数,它的功能就是拿第二个参数替换匹配的值。

  1.replace(regexp, string):我想把“乐小天”中的“小”替换成“大”,如下所示。

console.log("乐小天".replace(/小/g, "大"));//乐大天

//trim的实现方式
console.log(" 乐小天 ".replace(/(^\s+)|(\s+$)/g, ""));//乐小天

  2.replace(regexp, fn);fn这个回调函数可以有四种参数,第一种参数是匹配regexp的字符串;第二种为匹配regexp子表达式的字符串(有几个自表达式,顺延对应几个参数,如果没有子表达式,则第二个参数为第三种参数);第三种参数为regexp匹配字符串在字符串中的索引;第四种参数为当前调用replace的字符串。

  拿上面trim的实现为例,它的正则表达式包含两个子表达式:(^\s+)和(\s+$);所以回调函数应该有5个参数。当然,如果没有子表达式,则只有三种参数。

console.log("        乐小天    ".replace(/(^\s+)|(\s+$)/g,
function(match, matchChild1, matChild2, index, strObj){
console.log("match:" + match + ";");
console.log("matchChild1:" + matchChild1 + ";");
console.log("matChild2:" + matChild2 + ";");
console.log("index:" + index + ";");
console.log("strObj:" + strObj + ";");
return "";
}
));
/**
match: ;
matchChild1: ;
matChild2:undefined;
index:0;
strObj: 乐小天 ;
match: ;
matchChild1:undefined;
matChild2: ;
index:11;
strObj: 乐小天 ;
乐小天
*/

二、String.format的实现

  有的时候我们事先不知道字符串对应位置应该替换成什么,所以我们用占位符“{数字}”在字符串中进行预先占位,在真正确定的时候才将其替换掉。说白了就是将未知的替换字符封装成参数,让替换逻辑这个不变的部分与替换参数这个变化部分进行分离。

  1.format实现:

//扩展format
String.prototype.format = String.prototype.format || function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
}; console.log("{0}是个{1}帅哥!".format('孙悟空', '大'));//孙悟空是个大帅哥!

  2.format替换字符在form校验中用到的比较多,比如前端UI框架MiniUI的校验对象VType是这么定义的:

mini.VTypes = {
minDateErrorText : "Date can not be less than {0}",
maxDateErrorText : "Date can not be greater than {0}",
...
};

  在返回错误信息的时候将对应的边界值替换掉“{0}”

  

  

String.replace与String.format的更多相关文章

  1. [转]String.Replace 和 String.ReplaceAll 的区别

    JAVA 中的 replace replaceAll 问题: 测试code System.out.println("1234567890abcdef -----> "+&qu ...

  2. JAVA中string.replace()和string.replaceAll()的区别及用法

    乍一看,字面上理解好像replace只替换第一个出现的字符(受javascript的影响),replaceall替换所有的字符,其实大不然,只是替换的用途不一样.    public String r ...

  3. Java基础知识强化35:String类之String的其他功能

    1. String类的其他功能: (1)替换功能: String replace(char old, char new) String replace(String old,String new) ( ...

  4. Java String 函数常用操作 & format() 格式化输出,代码详解

    package _String_; import java.util.*; import java.math.*; import java.lang.*; public class _Strings ...

  5. format not a string literal and no format arguments

    今天cocos2d-x打包 android的时候报错:format not a string literal and no format arguments 报错点是:__String::create ...

  6. string中Insert与Format效率对比、String与List中Contains与IndexOf的效率对比

    关于string的效率,众所周知的恐怕是“+”和StringBuilder了,这些本文就不在赘述了.关于本文,请先回答以下问题(假设都是基于多次循环反复调用的情况下):1.使用Insert与Forma ...

  7. Android studio2.2 ndk 错误 :format not a string literal and no format arguments!

    在Android Studio2.2 进行NDK编程,在对*char 字符串 进行日志输出时,报错: error: format not a string literal and no format  ...

  8. cocos2dx android版本移植时的Error format not a string literal and no format arguments解决方案

    原文地址 : http://www.cnblogs.com/hhuang2012/p/3336911.html cocos2dx android版本移植时的Error format not a str ...

  9. std::string stringf(const char* format, ...)

    std::string stringf(const char* format, ...){ va_list arg_list; va_start(arg_list, format); // SUSv2 ...

随机推荐

  1. js日期转换工具

    var dq = new Date();//定义当前时间var sDueDate = formatDate(dq);/调用日期转换方法 传入当前时间 //进行日期转换 function formatD ...

  2. java学习笔记—实现一个类MyInputStream(28)

    1 实现一个类MyInputStream读取文件,且不能抛出异常 public class TestDemo { public static void main(String[] args) thro ...

  3. @media媒体查询

    @media媒体查询 @media screen and (min-width:640px) and (max-width:1920px){/*当屏幕尺寸大于640px时与小于1920时*/ .pub ...

  4. vue 生命周期 笔记

    生命周期:一个组件从创建到销毁的这个过程叫做生命周期 生命周期钩子函数   1.组件从创建到销毁的过程 1.创建前 创建后 2.挂载前 挂载后 3.更新前 更新后 4.销毁前 销毁后 beforeCr ...

  5. CSRF漏洞原理说明与利用方法

    翻译者:Fireweed 原文链接:http://seclab.stanford.edu/websec/ 一 .什么是CSRF Cross-Site Request Forgery(CSRF),中文一 ...

  6. bad interpreter: Text file busy

    刚才运行test_mysql.py文件的时候 报了个这样的错.上网查了下,链接在这里:http://www.cnblogs.com/kerrycode/p/4038934.html 于是我就把第一行的 ...

  7. LINUX中软RAID的实现方案

    转自linux就该这么学 应用场景 Raid大家都知道是冗余磁盘的意思(Redundant Arrays of Independent Disks,RAID),可以按业务系统的需要提供高可用性和冗余性 ...

  8. Metal Programming Guide

    读苹果文档时的笔记,给自己看. primary goal of Metal is to minimize the CPU overhead incurred by executing GPU work ...

  9. Python标准库中的生成器函数

    一.用于过滤的生成器函数 - 从输入的可迭代对象中产出元素的子集,而不修改元素本身 import itertools l1 = [1,2,3,4,5] l2 = [True,False,True,Fa ...

  10. css中代码格式以及@import的语法结构

    CSS中代码格式 CSS是Cascading Style Sheets(层叠样式表)的缩写.是一种对web文档添加样式的简单机制,属于表现层的布局语言. 1.基本语法规范分析一个典型CSS的语句: p ...