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




substr() - FUNCTION


substr() Function


The substr() 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 substr() function


Example :



<html>
<body>  
<script>

	var x = "Hello"
	var y = x.substr(1,3)
	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.substr(1,3)

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.substr(1,3) picks the value from position 1 till the position of the l. i.e. The position of second l is 3.


So, the statement x.substr(1,3) simply refers, "Pick the chunk from position 0 to position 3".


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.substr(2)
	document.write(y)
    
</script>      
</body>
</html>


Output :



  llo