Search & replace of part of string by replace methodHere is the syntax of replace method
Let us try with a simple string replace example.
The output of the above code is Welcome to JavaScript tutorial section to learn PHP You can see we have successfully replaces the first occurrence of the word PHP ( search string here ) with JavaScript ( replace string). The second occurrence of the string PHP is not replaced. So this way we can replace only one or the first find only. To replace all the matching search string we have to declared as global & use the regular expression syntax / in place of double quotes. Here is the code to search and replace all occurrence string.
The output of above code will be Welcome to JavaScript tutorial section to learn JavaScript You must have observed this search and replace of string is case sensitive so if we replace search string by lower case text ( php ) then it will not able to match the string and replace with JavaScript. So we will modify the code little bit and add i to the command to make it case insensitive string replace. . msg=msg.replace(/php/gi,"JavaScript"); The full code is here.
Now both the replacements have worked and the output is here Welcome to JavaScript tutorial section to learn JavaScript Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
![]() | ||
| ||