javascript replace multiple keyword

javascript

To replace multiple keywords in a string using JavaScript, you can use the replace function and specify a regular expression as the search pattern. For example:

let str = "The cat in the hat.";
let newStr = str.replace(/cat|hat/g, "dog");
console.log(newStr);  // Output: "The dog in the dog."

In the example above, the replace function searches for the cat and hat keywords and replaces them with dog. The g flag is used to perform a global search, so all occurrences of cat and hat in the string will be replaced.

You can specify as many keywords as you want in the regular expression by separating them with the | symbol. The replace function will replace all occurrences of any of the keywords with the replacement string.

For example:

let str = "The cat in the hat. The cat in the hat.";
let newStr = str.replace(/cat|hat/g, "dog");
console.log(newStr);  // Output: "The dog in the dog. The dog in the dog."