字符串的替换函数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. leetcode 罗马数字转整数

    罗马数字包含以下七种字符:I,V,X,L,C,D 和M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做II ,即为两个并列的 1.1 ...

  2. Kali Linux安全渗透-从入门到精通

    Kali-Linux是基于Debian Linux发行版 针对高级渗透测试和安全审计系统.带你一起从入门到精通. 什么是Kali-Linux? kali 包含几百个软件用来执行各种信息安全的任务,如渗 ...

  3. Struts2的优点与Struts1的区别:

    单实例与多实例有状态就是有数据存储功能,比如购物车,买一件东西放进去,可以再次购买或者删减.无状态就是一次操作,不能保存数据. 有状态对象,就是有成员属性的对象,可以保存数据,是非线程安全的.无状态对 ...

  4. 第三天,爬取伯乐在线文章代码,编写items.py,保存数据到本地json文件中

        一. 爬取http://blog.jobbole.com/all-posts/中的所有文章     1. 编写jobbole.py简单代码 import scrapy from scrapy. ...

  5. Haproxy搭建Web群集

    一.Haproxy与LVS LVS不支持正则处理,不能实现动静分离,对于大型网站,LVS的实施配置复杂,维护成本相对较高 Harpoxy是一款可提供高可用性,负载均衡.及基于TCP和HTTP应用的代理 ...

  6. 如何使用robots禁止各大搜索引擎爬虫爬取网站

    ps:由于公司网站配置的测试环境被百度爬虫抓取,干扰了线上正常环境的使用,刚好看到每次搜索淘宝时,都会有一句由于robots.txt文件存在限制指令无法提供内容描述,于是便去学习了一波 1.原来一般来 ...

  7. power designer和uml应用

    1.power designer和uml应用,它们可以帮助我们画图power designer还能在画图时帮助你完成代码.对于新手是很合适的一个画图工具, 2.这就是power designer 的示 ...

  8. 晦涩难懂的shell命令

    初学shell脚本,过程中发现许多不易于理解的脚本语言,网上各种查找学习之后,择优精简一番,做出以下总结,方便以后遗忘了回顾,也为像我一样的初学者提供方便——推荐给初学者的一本书:<Linux ...

  9. leetcode-268-Missing Number(异或)

    题目描述: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is ...

  10. CSS03--框模型、定位position、浮动

    我们接着“CSS02”,继续学习一些新的样式属性. 1.框模型:   规定了元素框处理  元素内容.内边距(padding).边框(border).外边距(margin,可以是负值)的方式 2.内边距 ...