javascriptreactjsstring

How can I replace multiple substrings with strings from multiple related arrays?


In JS, I am trying to manipulate a long plain string. I want to add new chars to each match inside the string in order to make a new string. I mean there are multiple values of the searched substring inside the long string. Any ideas?

const string = "I am living in London.
I am living in Brighton.
I am living in Birmingham.
I am living in Paris.
I am living in Lyon.
I am living in Hamburg.
I am living in Berlin.
I am living in Münih."

const citiesGermany = [Berlin, Hamburg, Bonn, Bochum, Bremen, Münih, ...]
const citiesFrance = [Lyon, Paris, Nice, ...]
const citiesEngland = [London, Brighton, Birmingham, ...]

Every city inside the string, I want to replace its country. I mean the output will be:

newString = "I am living in England.
I am living in England.
I am living in England.
I am living in France.
I am living in France.
I am living in Germany.
I am living in Germany.
I am living in Germany."

Solution

  • const string = `I am living in London.
    I am living in Brighton.
    I am living in Birmingham.
    I am living in Paris.
    I am living in Lyon.
    I am living in Hamburg.
    I am living in Berlin.
    I am living in Münih.`
    
    const countryToCity = {
      'Germany': ['Berlin', 'Hamburg', 'Bonn', 'Bochum', 'Bremen', 'Münih'],
      'France': ['Lyon', 'Paris', 'Nice'],
      'England': ['London', 'Brighton', 'Birmingham']
    }
    
    let newString = string;
    
    Object.entries(countryToCity).forEach(([country, cities]) => 
      cities.forEach(city => newString = newString.replaceAll(city, country))
    )
    
    console.log(newString)