How to replace all occurrences of a substring in a string in JavaScript?
Hi everyone! I'm new to JavaScript and I've run into this problem: I need to replace all occurrences of a specific word or character in a string. I tried using the replace() method, but it only replaces the first match.
Here's an example of my code:
```javascript
let text = "I love JavaScript. JavaScript is cool!";
let newText = text.replace("JavaScript", "Python");
console.log(newText); // Outputs: "I love Python. JavaScript is cool!"
```
As you can see, only the first word "JavaScript" was replaced, while the second one remained. How can I make it so that all occurrences are replaced? I've heard that you can use regular expressions, but I'm not very familiar with them yet. Is there a simpler way? Or do I absolutely need to learn RegExp?
I would be grateful for a clear explanation with examples.
No answers yet.
Log in to leave an answer