Substrings in JavaScript

JavaScriptSubstring is basically a part of string which you want to extract from a given string.   There are 3 of methods in JavaScript which can do the job for you.

substring():  This method takes 2 parameters.  The first parameter is start and second parameter is end.  Both the parameters take a numerical value which represents the starting and ending position of a substring.  The end parameter is optional and if you do not provide it, then all characters from starting position will be extracted as substring.  The most interesting thing to notice here is that if the value of the end parameter is greater than start parameter then JavaScript will automatically swap those values and extract substring.   The only point to keep in mind here is that the index position of a string always starts from 0.

substr():  This method also takes 2 parameters.  The first parameter is start and second parameter is count or length of characters you want to extract from a given string.  The second parameter is optional and if you do not specify second parameter, then all characters from starting position will be extracted as substring.  This method does not work in IE8 or earlier versions.

slice():  This method works exactly same as substring() method.  But swapping of parameter values will not happen if end parameter is greater than start parameter.

All above 3 methods works fine as long as you know from where to start extraction process.  But in case, you are not sure about starting position and want to retrieve it dynamically, then you can use indexOf() method which will return index position of a substring.  IndexOf() method takes a string value as a parameter.  If the value is found, it will return index position of substring.  If the value is not found, it will return -1.  Example is given below.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Tutorial</title>  
</head>
<body>
<script type="text/javascript">
  
    var hello = "This is a hello world!" ;

    var  index = hello.indexOf("hello");

    document.write(hello.substring(index, 20) + "<br>");

    document.write(hello.substr(index, 12)  + "<br>");

    document.write(hello.slice(index, 22) + "<br>");

</script>
 
</body>
</html>