replace(): Search & replace of string

<script type="text/javascript">
var msg="Welcome to PHP tutorial section to learn PHP";
msg=msg.replace("PHP","JavaScript");
document.write(msg);
</script>
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.

<script type="text/javascript">
var msg="Welcome to PHP tutorial section to learn PHP";
msg=msg.replace(/PHP/g,"JavaScript");
document.write(msg);
</script>
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.
<script type="text/javascript">
var msg="Welcome to PHP tutorial section to learn PHP";
msg=msg.replace(/php/gi,"JavaScript");
document.write(msg);
</script>
Now both the replacements have worked and the output is here

Welcome to JavaScript tutorial section to learn JavaScript
Syntax
str_var.replace("search_string", "replace_string")

JavaScript String Reference Searching string
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer