Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




substring() - FUNCTION


substring() Function


The substring() Function is used to slice a substring from the given String. It doesn't accept negative indexes.


Say, you have a String Hello and you want to take ell from the String Hello and store it in a different variable.


Accessing a chunk of letters/characters from a String using substring() function


Example :



<html>
<body>  
<script>

	var x = "Hello"
	var y = x.substring(1,4)
	document.write(y)
    
</script>      
</body>
</html>


Output :



  ell

So, we want to take the chunk of letters/characters from the String Hello and store it into the variable y.


And in the first line, we have stored Hello inside x.


x = "Hello"
java_Collections


Also, let us see the elaborated structure.

java_Collections

So, we want to take the chunk ell from Hello. And that happens in the next line.


var y = x.substring(1,4)

Just note, the position of e from ell is 1 and the position of the last l from ell is 3.


So, the statement, x.substring(1,4) picks the value from position 1 till the position of the l plus 1. i.e. The position of second l is 3. We just add 1 to it.


So, the statement x.substring(1,4) simply refers, "Pick the chunk from position 1 to position (4-1)".


Note : The end position of x.substring(1,4) i.e. 4, might look a little weird. Looks like it should be 3 instead of 4. But that is the way it is.

And ell is assigned to the variable y.

java_Collections

And in the next line, we have the print statement,


document.write(y)

That prints the chunk of letters ell.

Output :



  ell

Again let us see, how can wee access the last 3 letters of the string i.e. llo.


Example :



<html>
<body>  
<script>

	var x = "Hello"
	var y = x.substring(2)
	document.write(y)
    
</script>      
</body>
</html>


Output :



  llo

There is a speciality of substring().


Say for example, by mistake you have given the opposite range to extract.


i.e.


Example :



<html>
<body>  
<script>

	var x = "Hello"
	var y = x.substring(4,1)
	document.write(y)
    
</script>      
</body>
</html>


Output :



  ell

Although we have given the opposite range to extract.


var y = x.substring(4,1)

But JavaScript makes an intelligent guess and extracts ell.