How to Replace String in JavaScript?

04-Dec-2019

.

Admin

Hi Guys,

In this tutorial ,We Will give you example of replace string using javascript. i can replace all string using javaScript method. we will explain the javascript string.replace() method with the definition of this method, syntax, parameters, and several examples

The JavaScript string replace() method searches a string for a specified value or a regular expression, or keyword, and replace match search string to given string, returns a new string

Syntax


string.replace(search_value, new_value);

Parameter Values

search_value :-

This is the first parameter and required. The value, or regular expression, that will be replaced by the given value

new_value :-

This is the second parameter and required. The given value to replace the search value.

I can blow you can easily replace string using javascript in this example.

Example Repalce Word

Here the contents of the string itsolutionstuff will be replaced with nicesnippets, In this example single string repalce.

<!DOCTYPE html>

<html>

<head>

<title>Replace String Using JavaScript - https://www.nicesnippets.com/</title>

</head>

<body>

<p>Click the button to replace "itsolutionstuff" with "nicesnippets" in the paragraph below:</p>

<p id="demo">Visit itsolutionstuff!</p>

<button onclick="myFunction()">Click Here</button>

<script>

function myFunction() {

var str = document.getElementById("demo").innerHTML;

var res = str.replace("itsolutionstuff", "nicesnippets");

document.getElementById("demo").innerHTML = res;

}

</script>

</body>

</html>

Example Repalce All Word

Here the contents of the string green will be replaced with red, In this example multipale string repalce.

<!DOCTYPE html>

<html>

<head>

<title>Repalce All String Using JavaScript - https://www.nicesnippets.com/</title>

</head>

<body>

<p>Click the button to replace "green" with "red" in the paragraph below:</p>

<p id="demo">Mr Green has a green house and a blue car.</p>

<button onclick="myFunction()">Click Here</button>

<script>

function myFunction() {

var str = document.getElementById("demo").innerHTML;

var res = str.replace(/green/gi, "red");

document.getElementById("demo").innerHTML = res;

}

</script>

</body>

</html>

I hope it can help you..

#JavaScript