'What is the best way to replace 2 possible strings with another string?
If the string starts with either foo.com or bar.me replace with baz.co. Is this the most efficient / concise way?
string1.replace('foo.com', 'baz.co').replace('bar.me', 'baz.co')
We could have an array of strings: ['foo.com', 'bar.me']
Solution 1:[1]
You can use a regular expression:
string1.replace(/foo\.com|bar\.me/, 'baz.co')
"Starts with" would require to anchor the expression:
string1.replace(/^(foo\.com|bar\.me)/, 'baz.co')
Solution 2:[2]
I understood you question. You would like to replace a couple of strings in an array with "baz.co". You have two arrays. 1) array with multiple strings. 2) array with string which you will replace (needle). And a string which you use for the replacement.
const arr = ['foo.com', 'bar.me', 'not.re'];
const nee = ['foo.com', 'bar.me']
const rep = 'baz.co'
const n = [];
arr.forEach(i => {
n.push( nee.includes(i) ? rep : i);
})
console.log(n)
Solution 3:[3]
I would suggest the solution of Felix Kling.
A more generalized way to solve such "chained" operations (In case that those can't be expressed with a RegExp) would be to use the Array.reduce functionality:
let string1 = 'bar.me.test'
string1 = ['foo.com', 'bar.me'].reduce((previousValue, valueFromArray) => {
return previousValue.replace(valueFromArray, 'baz.co')
}, string1);
console.log(string1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Felix Kling |
| Solution 2 | Maik Lowrey |
| Solution 3 |
