Javascript String Replace()

Javascript string replace() replaces a subtring with the new substring from a string by matching the substring element in the string. It takes two parameters.

Javascript String Replace() Syntax

string.replace(regexp or substr,newstring)

The first parameter in Replace function is the regular expression or string that we are attempting to replace.
And the second parameter is the new string that will be replace with. The result of the replaces can be stored in a javascript variable.

Javascript String Replace() Example

var javascript_var = “This is test for javascript string replace function. This is javascript string replace test. “;

javascript_var = javascript_var.replace(“javascript”, “js”);
alert(javascript_var);

Output would be an alert with new string: “This is test for js string replace function. This is javascript string replace test.”.

Note that only first occurrence of the string “javascript” has been replaced with the string “js”. To do global replacement, we can use regular expression as shown in next example:

Javascript String Replace() Regular Expression Example

var javascript_var = “This is test for javascript string replace function. This is javascript string replace test. “;

javascript_var = javascript_var.replace(“/javascript/g”, “js”);
alert(javascript_var);

Output would be an alert with new string: “This is test for js string replace function. This is js string replace test.”.

The first parameter in javascript string replace function is a regular expressions: /javascript/g.

Learn about regular expressions in Perl from the link.

css.php