How to replace char with a string with many characters

I want to change char string in a string with many values

I have a line like this:

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

And I want to replace ever% with a char, which is after, so the date variable should look something like this:

date_format="mm/dd/YY";

Here is what I have tried so far, but I can't get it to work, so I need 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));
+4
source share
5 answers

You can use the regular expression for this:

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

console.log(res);
Run codeHide result
+3
source

You can try the following:

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

Hope these are hepls.

+4
source

function act(str) {
  var res = "";
  for (var i = 0; i < (str.length - 1); i++) {
    if (str[i] === "%")
      res += str[i + 1];
    else
      res += str[i];
  }
  res += str[i];
  return res;
}
var date_format = "%m/%d/%Y";
console.log(act(date_format));
Hide result
+1

, date_format corrent_format. replaceon . date_format, :

for (var i = 0; i < my_locations.length; i++) {
  date_format = replaceon(date_format, my_locations[i], date_format[my_locations[i]+1])
}

, String.replace :

date_format.replace(/%(.)/g, '$1$1');
+1

/%(.)/g, '$1$1':

  • / , .
  • % %.
  • . , %. % m,% d /% Y.
  • (.), parens, , .
  • /g ( ).
  • ?1 , , (.).
  • ?1?1 .

, %. ., .

. , , . , , . (Dyslexia regex - .) , 47 , , , , , , , , .

, :

var x = '%m/%d/%y';
x = x.replace('%', 'm');
x = x.replace('%', 'd');
x = x.replace('%', 'y');
alert(x);

, replace .

, . . 20 , 20 , 15 . , , , , , ... , . . . , . , , , , .

+1

Source: https://habr.com/ru/post/1648896/


All Articles