javascript replace multiple keyword
javascriptTo 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."
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame