Final answer:
To switch 'cats' and 'dogs' in a string using JavaScript and regular expressions, you can use the replace() function with a regex pattern and a callback function that swaps the matched word.
Step-by-step explanation:
To switch 'cats' and 'dogs' in the given string using JavaScript and regular expressions, you can use the replace() function with a regular expression pattern and replacement string.
Here's an example code:
const originalString = 'Cats and dogs are lovely pets. Dogs are not smarter than cats. Cats are smarter than dogs.';
const modifiedString = originalString.replace(/(cats|dogs)/gi, function(match, p1) {
return p1 === 'cats' ? 'dogs' : 'cats';
});
console.log(modifiedString);
The regular expression pattern (cats|dogs) matches either 'cats' or 'dogs', and the callback function in the replace() method swaps the matched word with its counterpart.