+4 votes
157 views
by (3k points)

Substring method in JavaScript


1 Answer

+5 votes
by (3k points)

Learn to handle the substring () method that extracts characters from a string between two specified indices.

In this tutorial we will know the substring method in JavaScript, which allows you to extract characters from a string between two specified indices, know more about this method.

substring

The method substring () extracts the characters in a string between two specified indices, and returns a new substring. So if we have:

var data =  'Hello community Devcode' ;

How to use the substring method would be:

data . substring ( start , end ) ;

Where:

  • Home , is a mandatory value, which must be an integer between 0 and the length of the chain.
  • End , not mandatory value, and likewise, is an integer between 0 and the length of the chain.

exceptions:

  • If  I start , it is a number less than 0, will be considered as 0, consider this example:
  •  
data . substring ( - 1 , 2 ) ; 
"Ho"
  • To be the case, that  start  is equal to  end , then we will return an empty string, see:
  •  
data . substring ( 2 , 2 ) ; 
""
  • By omitting the parameter  order , then it will be taken as an index of chain length stop.
  •  
data . substring ( 5 ) ; 
"Devcode community"
  • If the parameter  start  is greater than  end , the method invest both values.
  •  
data . substring ( 15 ,  5 ) ; 
"community"
  • If both parameters are greater than the length of the chain, we will return an empty string.
  •  
data . substring ( 23 ,  24 ) ; 
""
  • When the parameter  start is greater than the length of the string, and the second is a value from the range set, the method will invest both values ​​and assign the parameter that has a past range value to the value of the length of the chain. 
  •  
data . substring ( 24 ,  5 ) ; 
"Devcode community"
  • If the parameter  order  is greater than the length of the string, then it will be assigned as stop the end of the chain.
  •  
data . substring ( 5 ,  30 ) ; 
"Devcode community"

Note : The substring () method does not modify the original string.

Example:   Some ways of using this method would be: 

var data =  'Hello community Devcode' ; 
for  ( var i =  0  ; i < data . length ; i ++ ) {
 console . log ( data . substring ( i ,  ( data . length ) )  ) ; 
}
 Hello community Devcode 
wave community Devcode 
the Devcode community 
to community Devcode 
Devcode community 
community Devcode 
ommunity Devcode 
Devcode community 
unit Devcode 
nity Devcode 
ity Devcode 
dad Devcode 
ad Devcode 
d Devcode 
Devcode 
evcode 
vcode 
code 
ode 
of 
e

In this tutorial we have learned subtring management () method, and the considerations that we must consider, I hope in next tutorial to learn more about JavaScript and others. Do not forget that in Devcode accounts with a number of courses to be a professional in web development. 


statcounter statistics counter
...