JavaScript 学习笔记 -- String.trim + format

最近仍在IE6徘徊,低版本的浏览器没有实现JavaScript 的trim() 和 format(). . 主要是这两个使用的比较多,先整理出来:

1、trim() -- 去除字符串中开始和结尾部分,所包含的指定字符。 默认是 空格; 参考: http://www.nowamagic.net/javascript/js_TrimInJavascript.php

 1 //prototype: trim
 2 String.prototype.trim = function(strToRemove){
 3     var reg = null;
 4     // to trim space character, when not passing the param
 5     if(strToRemove == null || strToRemove == undefined || strToRemove.length == 0){
 6         reg = /(^s*)|(s*$)/g;
 7     }
 8     else{
 9         reg = new RegExp("(^"+strToRemove+"*)|("+strToRemove+"*$)", "g");
10     }
11     return this.replace(reg, "");
12 }
13 //test: "abc,".trim(",") --- > abc

2、format() -- 格式化字符串(两种方式实现), 参考: http://www.cnblogs.com/nonlyli/archive/2008/08/14/1267480.html

A. 基于'实例'的方法,放在原型链上

1 //prototype: format
2 String.prototype.format = function() {
3     // need a variable to store the params to replace, or it will be overrided in the MatchedFunction
4     var args = arguments;    
5     return this.replace(/{(d+)}/g, function(m, i){ return args[i];});
6 }
7 //test: "abc{0}".format(123) --- > abc123

B. 基于'类'的方法,静态方法。 这个在原来的基础上做了更改,因为已经使用for循环了,再使用正则替换,感觉有点浪费了; 而且,这个方法和上一个只是,参数的位置不一致,向后移一位即可。。。

 1 //static: format
 2 String.format = function() {
 3     var args = arguments;
 4     if(args.length == 0){
 5         return "Argument null";
 6     }
 7     var source_str = args[0];
 8     return source_str.replace(/{(d+)}/gm, 
 9                             //attention:here, sub_index is String,need to convert to int when adding
10                             function(item_matched, sub_index){        
11                                 return args[parseInt(sub_index)+1];
12                             }
13             );
14 }
15 //test: String.format("abc{1}", "123", 999)  -- > abc999

这个format的静态方法,还有一个利用Slice的更巧妙的实现, 参考: http://witmax.cn/js-function-string-format.html

 1 //another ingenious method to replace, using the slice method of Array,
 2         // reference: http://witmax.cn/js-function-string-format.html
 3 String.format = function(source_str){
 4     var param_args = Array.prototype.slice.call(arguments, 1);
 5     return source_str.replace(/{(d+)}/gm,
 6                             function(item_matched, sub_index){        
 7                                 return param_args[sub_index];
 8                             }
 9             );
10 }
原文地址:https://www.cnblogs.com/ccding13/p/3581417.html