How to replace all occurrences of a string in JavaScript?

preview_player
Показать описание
Please do like share and comment if you like the video please do hit like and if you have any query please write it comment box
To replace all occurrences of a string in JavaScript, you can use the replace() method with a regular expression and the g flag. The g flag stands for "global" and will replace all occurrences of the string instead of just the first one.

let originalString = "Hello world, hello universe!";

In this example, the replace() method is called on the originalString variable with the regular expression /hello/gi and the replacement string "hi". The g flag is used to replace all occurrences of the string, and the i flag is used to make the search case-insensitive. The resulting string, "Hi world, hi universe!", is then assigned to the newString variable and printed to the console.

Note that replace() does not modify the original string. Instead, it returns a new string with the replacements made. If you want to modify the original string, you can assign the result back to the original variable:

You can support me by buying a coffee for me

Please do subcribe my other video tutorials
Thanks for watching

Have a Great Day !!!
Рекомендации по теме