You need to match both a
and b
with a regular expression, then use a function to distinguish whether it was an a
or an b
. See documentation for the replace function.
var str = 'abcde'
var newStr = str.replace(/[ab]/g, function (match) {
switch (match) {
case 'a':
return 'ab'
case 'b':
return 'c'
default:
return '???' // or throw error
}
})
console.log(newStr) // -> abccde
If you have a list of strings that you want to replace, you might want to look at how to escape strings to be used in regular expressions, then use the constructor for RegExp to construct the regular expression to be used for the replace function.
var replacements = {'a': 'ab', 'b': 'c'}
var keys = Object.keys(replacements)
// escapeRegExp function from https://stackoverflow.com/a/6969486/8557739
var escapedKeys = keys.map(escapeRegExp)
var re = RegExp(escapedKeys.join('|'), 'g') // re = /a|b/g
// then continue on like before
var str = 'abcde'
var newStr = str.replace(re, function (match) {
for (var key in replacements) {
if (match === key) {
return replacements[key]
}
}
return '???' // or throw error
})
console.log(newStr) // -> abccde