Javascript string functions: extracting parts of a string

Javascript string functions: extracting parts of a string

Retrieve a desired section of a string using Javascript string functions


Javascript comes equipped with several useful string functions with which we can manipulate and modify strings. There are three functions that allow us to extract parts of a string, each of these work similarly but have some key differences that are useful in different situations.


Extracting parts of a string with the substring() function


The substring function provides a way of extracting parts of a string by means of positional indexes, this function takes 2 arguments: a start index and an end index, these indexes represent the position of a certain character within the string starting from 0. This function will extract and return a new string from the given start index up to but not including the end index from the initial string. The end index parameter is optional, if this is not given then the substring function will simply extract from the start index to the end of the string.


string.substring(start, end);


Say we wanted to extract "among" from the string "Peace among worlds" then we could use the following statement:


var string1 = "Peace among worlds";   
var string2 = string1.substring(6, 11);   

If we wanted to extract the last word in this string, then we do not have to include an end index:


var string1 = "Peace among worlds";   
var string2 = string1.substring(12);

This will return the new string "worlds"


Extracting parts of a string with the substr() function


The substr() function works similarly to the substring() function, except instead of an end index, it takes the length of the string you wish to extract.


string.substring(start, length);


So if we again wanted to extract "among" from the string "Peace among worlds" then we could use the following statement:


var string1 = "Peace among worlds";   
var string2 = string1.substr(6, 5);


Extracting parts of a string with the slice() function


The slice() function works similarly to the substring() function, it also takes a start index and end index as arguments, except this function allows us to use negative indexes. Negative indexes allow us to select a character within a string starting from the back.


string.slice(start, end);


So if we wanted to extract "among" from the string "Peace among worlds" then we could use the following statement:


var string1 = "Peace among worlds";   
var string2 = string1.substr(-12, -7);

Or we can combine normal indexes with negative indexes:


var string1 = "Peace among worlds";   
var string2 = string1.substr(6, -7);



Christopher Thornton@Instructobit 7 years ago
or