OneBite.Dev - Coding blog in a bite size

replace multiple words in a string in Javascript

Code snippet on how to replace multiple words in a string in Javascript

  const sentence = 'This is a sentence that has multiple words that need to be replaced.';
  const replacements = {
    sentence: 'statement',
    words: 'terms',
    replaced: 'altered'
  };
 
  const newSentence = sentence.replace(/\w+/g, (word) => {
    return replacements[word] || word;
  });
 
  console.log(newSentence);
  // Output: This is a statement that has multiple terms that need to be altered.

This code starts by declaring a constant named sentence which stores a string of text. Next, a constant named replacements is declared which is filled with objects that contains the words that need to be changed and what they should be changed to. The .replace() method is then used to replace each instance of the words in the sentence with the new words from the replacements objects. The /w+/g is a regular expression which is used to find all the words in the sentence. The replace() method uses the arrow function to loop through the words in the sentence and compare them with the replacements objects. Finally, if the words are present in the replacements objects then they are replaced with the new word. The code then logs the new sentence with the replaced words.

javascript