SQL PHP HTML ASP JavaScript articles and free scripts to download
JavaScript String

Search & replace of part of string by replace method

We can update or replace part of a string by another string by using replace method of string. Here part of a string is searched first and then replaced with another specified string.

Here is the syntax of replace method
str_var.replace("search_string", "replace_string")
Let us try with a simple string replace example.
<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

Google+

Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked




Join Our Email List
Email:  
For Email Newsletters you can trust
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer