替换所有其他特定字符串

replace every other specific string

我希望能够使用某种函数替换字符串的所有其他实例,可能会像这样工作:

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

我试过搜索堆栈溢出的解决方案,但无济于事。

如果你想替换所有相同的字符串,你可以使用正则表达式;

let str = "gg gamers, abc gg gamers, def gg gamers..";
let out = str.replace(/gg gamers/g, "gs gamers");
console.log(out)

预先编辑(因为对要求进行了澄清更新)

以下基于 split 的方法背后的主要思想是使用具有单个捕获组的正则表达式,该捕获组以要替换的 character/string 为目标。因此,结果数组在每次匹配时都会被拆分,但也将匹配项作为单独的项目包含在内。

其余的是通过直接 mapping 实现的,其中 return 值是通过对提供的 nth 替换进行等式和基于模数的计数来选择的...

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; }

+++ 编辑结束+++

无需正则表达式和 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")
);

编辑

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

是的,原因..基于正则表达式然后...

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")
);

以下函数将替换所有其他特定字符串。它不需要字符串彼此相邻。请注意,匹配区分大小写。该函数的工作原理是在匹配的位置拆分输入字符串,然后通过更改插入的值重新插入匹配的部分。此外,该方法可以很容易地修改,以支持通过改变模运算 i % 2.

替换每第三、第四或 n:th 匹配项

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'))