Extension String:Format

If used c# you will found the function String.Format is a very powerfull string replacement method.express

But in js,there just offer a replace method,and only can replace the first string fit the pattern.c#

Ofcourse,you can use regular expressions to achive you goal.app

But it will makes your code ugly and hard to read.ide

So I extension String to make this point.this

As usual, here is the core code.prototype

String.prototype.Format = function() {
var returnValue = this;
for(vari = 0; i < arguments.length; i++) {
var arg = arguments[i];
var key = "";
var value = "";
//if string then find {i} to replace
if(typeof arg == "string") {
key = i;
value = arg;
} elseif(arg instanceofArray) {
//if array then trans param to params then recall
returnValue = returnValue.Format.apply(returnValue, arg);
continue;
} else{
//if object then use as keyvaluepair object
key = arg.key;
value = arg.value;
}
//setting translation symbol
var keySymple = [
{ reg: /\\/ig, value: "\\\\"},
{ reg: /\{/ig, value: "\\{"},
{ reg: /\}/ig, value: "\\}"},
{ reg: /\)/ig, value: "\\)"},
{ reg: /\(/ig, value: "\\("},
]
//translate translation symbol
for(var j = 0; j < keySymple.length; j++) {
varsympleReplace = keySymple[j];
key = key.toString().replace(sympleReplace.reg, sympleReplace.value);
}
var reg = newRegExp("\\{"+ key + "\\}", "ig");
returnValue = returnValue.replace(reg, value);
}
return returnValue;
}

Then the calling codecode

var demoStr="this is a {0} {1}"
demoStr.Format("hot","day")//return "this is a hot day"
demoStr.Format(["hot","day"])//return "this is a hot day"
var demoStr="my name is {Name},age {Age}"
demoStr.Format({key:"Name",value:"Happy"},{key:"Age",value:"20"})
//return "my name is Happy,age 20"
demoStr.Format([{key:"Name",value:"Happy"},{key:"Age",value:"20"}])
//return "my name is Happy,age 20"

param support params and array structureorm

and support string and keyvaluepair datastring

相關文章
相關標籤/搜索