我想像在 C# 中一样编写 JavaScript 函数 strinformat。
function gg_stringformat(){
argcount=arguments.length;
if (argcount==0) {
return "";
}
else if (argcount==1){
return arguments[0];
}
else {
original =arguments[0];
for (var i=1; i<argcount;i++) {
strtoreplace='{'+(i-1)+'}';
strreplacewith=arguments[i];
original=original.replace('/%' + strtoreplace + '%/gi',strreplacewith);
}//for
return original;
}
}
当我使用 original=original.replace( strtoreplace , strreplacewith);
它工作正常但仅替换第一次出现。
上面的代码根本不起作用。我必须做什么?
最佳答案
一些注释:
在函数顶部声明所有变量,
使用以后有意义的变量名,
为正则表达式取一个构造器,
RegExp
转义具有特殊含义的字符,如大括号的开头,
new RegExp('\\{' + (i - 1) + '}', 'gi') // ^^^
提前退出,不要在之前使用
return
语句使用else
,因为这会结束函数。
function gg_stringformat() {
var argcount = arguments.length,
string,
i;
if (!argcount) {
return "";
}
if (argcount === 1) {
return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;
}
console.log(gg_stringformat("My name is {0}, My age is {1}", "George Gogiava", 35));
关于JavaScript string.replace 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48126316/