In the last tutorial we continued our discussion on String Objects in JavaScript. Hopefully we will wrap it up in this episode. We left off with the Match() method, which allowed us to search a string and return the same string if it was present in our variable, or return a null value if it was not. We will pick back up with the Replace() method.
JavaScript Objects: Finishing Strings - The Slice() Method (Page 4 of 6 )
The Slice() method is used when you want to divide up a pizza into separate portions. It is also used when you wish to extract or slice a part of a string and return it to a new string.
<html>
<body>
<script type="text/javascript">
var castle="Castle Greyskull!"
document.write(castle.slice(6))
document.write("<br />")
</script>
</body>
</html>
This code finds the text in the sixth string and returns it, resulting in:
Greyskull!
If we wanted to grab more than one value, we do it like this:
<html>
<body>
<script type="text/javascript">
var castle="Castle Greyskull!"
document.write(castle.slice(6))
document.write("<br />")
document.write(castle.slice(0,17))
document.write("<br />")
document.write(castle.slice(0,15))
</script>
</body>
</html>
This results in the following manner:
Greyskull! Castle Greyskull! Castle Greyskul
You will note that in the last criteria, I used the value 15, and hence we only got part of the word Greyskull, or Greyskul.