我想改变一个字符串中有很多值的字符
我有这样的字符串:
date_format = "%m/%d/%Y";
我想用之后的字符替换 %,所以日期变量应该是这样的:
date_format="mm/dd/YY";
到目前为止,这是我尝试过的方法,但我无法让它工作,所以我需要一些帮助:
function replaceon(str, index, chr) {
if (index > str.length - 1) return str;
return str.substr(0, index) + chr + str.substr(index + 1);
}
function locations(substring, string) {
var a = [],
i = -1;
while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i);
return a;
}
function corrent_format(date_format) {
var my_locations = locations('%', date_format);
console.log(my_locations.length);
for (var i = 0; i < my_locations.length; i++) {
replaceon(date_format, my_locations[i], date_format[my_locations[i] + 1]);
}
return date_format;
}
console.log(corrent_format(date_format));
最佳答案
你可以试试这个:
"%m/%d/%Y".replace(/%([^%])/g,"$1$1")
希望这个hepls。
关于javascript - 如何用多个字符替换字符串中的一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547086/