Mostafa Mohamed Mostafa Mohamed - 4 months ago 7
Javascript Question

how to replace a char in string with many chars

I want to change a char in string with many values

I have string like this :

date_format = "%m/%d/%Y";


And i want to replace ever % with the char which after, so the date variable should be like this:

date_format="mm/dd/YY";


Here is what I tried so far, but i can't get it to work, so I need some help here:

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));

Answer

You can use a regular expression for that:

var date_format="%m/%d/%Y";
var res = date_format.replace(/%(.)/g, "$1$1");

console.log(res);

Comments