Mostafa Mohamed Mostafa Mohamed - 1 year ago 89
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:


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);
for (var i = 0; i < my_locations.length; i++) {
replaceon(date_format, my_locations[i], date_format[my_locations[i] + 1]);
return date_format;


Answer Source

You can use a regular expression for that:

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download