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);

Here,

  • 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.

Examples:

    Input:
    str = "Hello world!"
    find = "Hello"
    replace = "Hi"
    Output:
    "Hi world!"

Code:

<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!





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.