Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 653
Mostafa Mohamed Avatar asked Jul 23 '16 22:07

Mostafa Mohamed


1 Answers

You can try this:

"%m/%d/%Y".replace(/%([^%])/g,"$1$1")

Hope this hepls.

like image 179
Georgi Naumov Avatar answered Sep 21 '22 15:09

Georgi Naumov