JavaScript substring() Method
The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
This method extracts the characters in a string between "from" and "to", not including "to" itself.
Syntax:
--------------------------------------------
string.substring(from, to)
--------------------------------------------
Example:
<script type="text/javascript">
var str="Hello world!";
document.write(str.substring(3)+"<br />");
document.write(str.substring(3,7));
</script>
The output of the code above will be:
----------------------------------
lo world!
lo w
----------------------------------
split()
The split() method is used to split a string into an array of substrings, and returns the new array.
Syntax
----------------------------------
string.split(separator, limit)
----------------------------------
where
1)separator is Optional.It specifies the character to use for splitting the string. If omitted, the entire string will be returned
2)limit is Optional.It is an integer that specifies the number of splits
<script type="text/javascript">
var str="How are you doing today?";
document.write(str.split() + "<br />");
document.write(str.split(" ") + "<br />");
document.write(str.split("") + "<br />");
document.write(str.split(" ",3));
</script>
The output of the code above will be:
------------------------------------------
How are you doing today?
How,are,you,doing,today?
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
How,are,you
------------------------------------------
String Replace
<script type="text/javascript">
var visitorName = "Chuck";
var myOldString = "Hello username! I hope you enjoy your stay username.";
var myNewString = myOldString.replace("username", visitorName);
document.write("Old string = " + myOldString);
document.write("<br />New string = " + myNewString);
</script>
Output:
Old string = Hello username! I hope you enjoy your stay username.
New string = Hello Chuck! I hope you enjoy your stay username.