Home > other >  replace every other specific string
replace every other specific string

Time:10-30

I want to be able to replace every other instance of a string using some sort of function, maybe working something like this:

replace_every_other("i like ice cream","i","1")
// output => i l1ke ice cream
function replace_every_other(string, replace_string, replace_with) {
     ...
}

CodePudding user response:

if you want to replace all same string, you can use regEx;

let str = "gg gamers, abc gg gamers, def gg gamers..";
let out = str.replace(/gg gamers/g, "gs gamers");
console.log(out)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The following function will replace every other specific string. It does not require the strings to be next to each other. Note that the match is case-sensitive. The function works by splitting the input string at matched positions and then reinserting the matched parts by altering the value inserted. Additionally, the approach could be easily modified to support replacement of every third, fourth or n:th match by altering the modulus operation i % 2.

function replace_every_other(value, search, replacement) {
  // Replace every odd search match by the replacement string.
  // Return string.

  // First, split to parts at the matched strings.
  // This will remove all instances of the search string.
  var parts = String(value).split(search)

  // Handle empty strings strings with no matches.
  if (parts.length < 2) {
    return parts.join('')
  }

  // Insert between parts and
  var replacedParts = []
  for (var i = 0; i < parts.length; i  = 1) {
    // Add non-matched part
    replacedParts.push(parts[i])
    // Skip the end of value
    if (i !== parts.length - 1) {
      if (i % 2 === 0) {
        replacedParts.push(search)
      } else {
        replacedParts.push(replacement)
      }
    }
  }

  return replacedParts.join('')
}

// Testing
console.log('("i like ice cream", "i", "1") => ',
  replace_every_other('i like ice cream', 'i', '1'))
console.log('("i LIKE ice cream", "i", "1") => ',
  replace_every_other('i LIKE ice cream', 'i', '1'))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

prepended edit (since there was a clarifying update to the requirements )

The main idea behind the following split based approach is to utilize a regex with a single capture group which targets the to be replaced character/string. Thus the result array gets split at every match but also contains the very match as a separate item.

The rest is achieved by a straightforward mapping where the return value is chosen by equality and modulo based counting of the provided nth replacement ...

function replaceEveryNth(value, search, replacement, nthCount = 1) {
  let matchCount = 0;

  return String(value)
    .split(
      RegExp(`(${ search })`)
    )
    .map(str =>
      ((str === search) && (  matchCount % nthCount === 0))
        ? replacement
        : str 
    )
    .join('');
}

console.log(
  '("i like ice cream", "i", "1") =>',
  replaceEveryNth("i like ice cream", "i", "1")
);
console.log(
  '("i like ice cream", "i", "1", 2) =>',
  replaceEveryNth("i like ice cream", "i", "1", 2)
);
console.log(
  '("i like ice cream", "i", "1", 3) =>',
  replaceEveryNth("i like ice cream", "i", "1", 3)
);
console.log(
  '("i like ice cream", "i", "1", 4) =>',
  replaceEveryNth("i like ice cream", "i", "1", 4)
);
console.log('\n');


console.log(
  '("i like ice cream less", "e", "y", 2) =>',
  replaceEveryNth("i like ice cream less", "e", "y", 2)
);
console.log(
  '("i like ice cream less", "e", "y", 3) =>',
  replaceEveryNth("i like ice cream less", "e", "y", 3)
);
console.log('\n');


console.log(
  '("foo bar baz bizz boozzz", "o", "0", 2) =>',
  replaceEveryNth("foo bar baz bizz boozzz", "o", "0", 2)
);
console.log(
  '("foo bar baz bizz boozzz", "z", "ss", 2) =>',
  replaceEveryNth("foo bar baz bizz boozzz", "z", "ss", 2)
);
console.log(
  '("foo bar baz bizz boozzz", "zz", "S", 2) =>',
  replaceEveryNth("foo bar baz bizz boozzz", "zz", "S", 2)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

end of edit

This task can be achieved without regex and String.prototype.replaceAll ...

function replaceEveryOther(value, search, replacement) {
  return String(value)
    .replaceAll(
      [search, search].join(''),
      [search, replacement].join('')
    );
}

console.log(
  '("gg gamers foo buuuzz", "g", "s") =>',
  replaceEveryOther("gg gamers foo buuuzz", "g", "s")
);
console.log(
  '("gg gamers foo buuuzz", "o", "r") =>',
  replaceEveryOther("gg gamers foo buuuzz", "o", "r")
);

console.log(
  '("gg gamers foo buuuzz", "u", "n") =>',
  replaceEveryOther("gg gamers foo buuuzz", "u", "n")
);
console.log(
  '("gg gamers foo buuuuzz", "u", "n") =>',
  replaceEveryOther("gg gamers foo buuuuzz", "u", "n")
);

console.log(
  '("gg gamers foo buuuuzz", "uu", "U") =>',
  replaceEveryOther("gg gamers foo buuuuzz", "uu", "U")
);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Edit

"Is there a way to use this in Node.js? (as replaceAll isn't usable)"

yes, of cause .. regex based then ...

function replaceEveryOther(value, search, replacement) {
  return String(value)
    .replace(
      RegExp(`${ search }${ search }`, 'g'),
      `${ search }${ replacement }`
    );
}

console.log(
  '("gg gamers foo buuuzz", "g", "s") =>',
  replaceEveryOther("gg gamers foo buuuzz", "g", "s")
);
console.log(
  '("gg gamers foo buuuzz", "o", "r") =>',
  replaceEveryOther("gg gamers foo buuuzz", "o", "r")
);

console.log(
  '("gg gamers foo buuuzz", "u", "n") =>',
  replaceEveryOther("gg gamers foo buuuzz", "u", "n")
);
console.log(
  '("gg gamers foo buuuuzz", "u", "n") =>',
  replaceEveryOther("gg gamers foo buuuuzz", "u", "n")
);

console.log(
  '("gg gamers foo buuuuzz", "uu", "U") =>',
  replaceEveryOther("gg gamers foo buuuuzz", "uu", "U")
);
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related