Extension String:Format
2379 ワード
If used c脽you will found the function String.Format is a very powerfull string replaccement method.
But in js、there just offer a replace method、and only can replace the first string fit the pattern.
Ofcourse,you can use reglar expressions to achive you goal.
But it will makes your code ugly and hard to read.
So I extension String to make this point.
As usual,here is the code.
and support string and keyvaluepair data
But in js、there just offer a replace method、and only can replace the first string fit the pattern.
Ofcourse,you can use reglar expressions to achive you goal.
But it will makes your code ugly and hard to read.
So I extension String to make this point.
As usual,here is the code.
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;
}
The n the caling codevar 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 structureand support string and keyvaluepair data