August 17, 2024
JavaScript String Replace
You can replace a word or even a string from a string through replace method of string object in JavaScript. replace method required two string parameter to make replacement on the string first parameter old string which you want to replace and second parameter is new string which you want to replace with old string. You can also make replacement on the basis of regular expression. You can pass regular expression as arguments to replace method. The example of replace method mentioned below:
Code
<html>
<head>
<title>Replace Method Example</title>
</head>
<body>
<script language='JavaScript' type='text/Javascript'>
var greetingStr = 'Good Morning';
var result = greetingStr.replace( 'Morning', 'Evening');
</script>
</body>
</html>
In above mentioned example, we have a string object with the name of greetingStr and we make a replacement with replace method, we replaced Morning with Evening.
You can also make replacement on the basis of regular expression. You can pass regular expression as arguments instead of string value. Syntax mentioned below:
Code
yourStringObject.replace( regularExpression1, regularExpression2);