Home > Software engineering >  How can I insert a character after every n characters in javascript from backwards?
How can I insert a character after every n characters in javascript from backwards?

Time:04-23

A function that will insert 1st parameter after n(2nd argumanet)th times from backward

const string = "abcdefg";
const backWardInsert = (str, num) => {
  // Do the stuffs
  // Here is what I"ve tried
  const newStr = string.replace(/(.{3})/g, "$-1$");
  return newStr;
};
const result = backWardInsert("$", 3);
// result should be "a$bcd$efg"
console.log(result);

CodePudding user response:

You could take a positive lookahead and add dollar sign

https://regex101.com/r/fYrSJD/1

const string = "abcdefg";

const backWardInsert = (str, num) => {
  return string.replace(new RegExp(`.{1,${num}}(?=(.{${num}}) $)`, "g"), `$&${str}`);
};

const result = backWardInsert("$", 3);
console.log(result);

CodePudding user response:

Maybe it is that what you want

const string = "abcdefg";
const backWardInsert = (str, num) => {
  const regex = new RegExp(`(.{${num}})`, "gi");
  const newStr = string
    .split("")
    .reverse()
    .join("")
    .replace(regex, "$1"   str)
    .split("")
    .reverse()
    .join("");
  return newStr;
};
const result = backWardInsert("$", 3);
console.log(result);

  • Related