In JavaScript, we can replace a part of a string with a specified string by replacing it, this article shows the detailed use of replace, and shows you how to make partial, full, and case-insensitive substitutions with examples.
In JavaScript, we can replace a part of a string with a specified string by replacing the Replace function.
The following is the basic syntax for the Replace function:
Str_var.replace ("search_string", "replace_string")
Let's look at a simple example:
<Scripttype= "Text/javascript"> varmsg="Welcome to PHP tutorial sections to learn php-sharejs.com"; msg=Msg.replace ("PHP","JavaScript");d ocument.write (msg); </Script>
The output is:
Welcome to JavaScript tutorial sections to learn Php-sharejs.com
As you can see, this code we successfully replaced the first PHP for JavaScript. But the second PHP is still there, so this method can only replace the first matching string found. If we want to replace all of them, we need to replace them with regular expressions.
The following code can replace all specified strings:
<Scripttype= "Text/javascript">varmsg="Welcome to PHP tutorial sections to learn php-sharejs.com"; msg=Msg.replace (/PHP/G,"JavaScript");d ocument.write (msg);</Script>
The output is:
Welcome to JavaScript tutorial sections to learn Javascript-sharejs.com
It is important to note that this code is case-sensitive for replacement strings, i.e. PHP is replaced, but PHP is not replaced. If you want to be insensitive to case, you need to add an I command as follows:
Msg=msg.replace (/php/gi, "JavaScript");
The complete code is as follows:
<Scripttype= "Text/javascript">varmsg="Welcome to PHP tutorial sections to learn php-sharejs.com"; msg=Msg.replace (/PHP/gi,"JavaScript");d ocument.write (msg);</Script>
So two PHP will be replaced with JavaScript and case-insensitive
Welcome to JavaScript tutorial sections to learn Javascript-sharejs.com
Search and replace a specified string with the Replace function in JavaScript