How to replace all occurrences of a substring in a string in JavaScript?
Hello! I'm new to JavaScript and encountered a problem while working with strings. I need to replace all occurrences of a specific word in the text, but for some reason only the first match is replaced.
Here's my code:
```javascript
let text = "Кошка гуляет по крыше. Кошка любит молоко. Кошка спит на диване.";
let newText = text.replace("Кошка", "Собака");
console.log(newText);
// Outputs: "Собака гуляет по крыше. Кошка любит молоко. Кошка спит на диване."
```
As you can see, only the first word "Кошка" was replaced, while the rest remained unchanged. I tried looking in the documentation, but it mentions something about regular expressions, which I don't understand yet.
Is there a simple way to replace all occurrences without using complex constructs? Or is it impossible without regular expressions?
No answers yet.
Log in to leave an answer