Home > front end >  What is the best way to replace 2 possible strings with another string?
What is the best way to replace 2 possible strings with another string?

Time:03-24

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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)

  • Related