Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javascript-array JavaScript array replace element

Related Tutorials


 
 

Share on Google+Share on Google+

JavaScript array replace element

Advertisement
In the JavaScript array there is not any in-built replace() methods for replacing elements but we can implement replace() method by using the in-built splice() method. We have already discussed the splice() method in our JavaScript array tutorial.

JavaScript array replace element

     

In the JavaScript array there is not any in-built replace() methods for replacing elements but we can implement replace() method by using the in-built splice() method. We have already discussed the splice() method in our JavaScript array tutorial. For implementation of replace() method we have created a replace() method which takes three arguments as given below:

  • arrayName: Array Object at which replacement is to be done. 
  • repalceTo: array element to which we have to replace in the array 
  • replaceWith: array element against which replacement is to be done

 

 

 

function replace(arrayName,replaceTo, replaceWith)
{
  for(var i=0; i<arrayName.length;i++ )
  {  
  if(arrayName[i]==replaceTo)
  arrayName.splice(i,1,replaceWith);  
  }  
}

Above code is the function defined for implementing replace() method. 

replace(arr,"Suman","Vineet"); Here we have passed "Vineet" to be replaced by the array element "Suman".

Full code of javascript_array_replace.html is as follows:

<html>
  <head>
  <title>
 JavaScript array replace
  </title>
 <script type="text/javascript">
 var arr = new Array(5);
  arr[0]="Sandeep";
  arr[1]="Suman";
  arr[2]="Saurabh";
  arr[3]="Vinod";
  arr[4]="Amar";

function replace(arrayName,replaceTo, replaceWith)
{
  for(var i=0; i<arrayName.length;i++ )
  {  
  if(arrayName[i]==replaceTo)
  arrayName.splice(i,1,replaceWith);  
  }  
}
  document.write("<b>Before Replacement</b>=>"+arr+"<br>");
 replace(arr,"Suman","Vineet");
  document.write("<b>After Replacement</b>=>"+arr+"<br> ");
</script>
</head>
<body bgcolor="#ffffdd">
  <h2>
  <font color="blue">
  Example of implementing replace()<br>
  method on JavaScript Array
  </font>
  </h2>
</body>
</html>

Output of the example is as follows:

Download Sample Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 11, 2008

Related Tutorials

Discuss: JavaScript array replace element   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com