167k views
2 votes
String matching. write javascript program Use regular expression to switch cats and dogs in the following string: ""Cats and dogs are lovely pets. Dogs are not smarter than cats. Cats are smarter than dogs."" Your code should print ""Dogs and Cats are lovely pets. Cats are not smarter than dogs. Dogs are smarter than cats."".

User Shantr
by
8.4k points

1 Answer

4 votes

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.

User Hans Yulian
by
8.1k points