Home »
        JavaScript
    
    String replace() Method with Example in JavaScript
    
    
    
    
        JavaScript String replace() Method: Here, we are going to learn about the replace() method of string in JavaScript with Example.
        
            Submitted by IncludeHelp, on February 05, 2019
        
    
    
    String replace() Method
    replace() Method is a string method, it is used to replace a given part of the string in another given string and returns new string.
        
Syntax
            
    new_string = str.replace(find, replace);
    
    
    Parameters
    
        - str is the main string in which we have to perform the replacements.
- find is the substring to be replaced in the string.
- replace is the substring to be replaced.
- new_string is the retuned string after the replacement find with replace.
Sample Input/Output
    
    Input:
    str = "Hello world!"
    find = "Hello"
    replace = "Hi"
    Output:
    "Hi world!"
Example
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>		
	var main_str = "Hello world!";
	var find = "Hello";
	var replace = "Hi";
	//calling the function
	var new_str = main_str.replace(find, replace);
	document.write("string before replacement: " + main_str + "<br>");
	document.write("string after replacement: " + new_str + "<br>");
</script>
</body>
</html>
Output
string before replacement: Hello world!
string after replacement: Hi world!
	JavaScript String Object Methods »
	
	
    
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement