Almost in every IT job interview, the interviewers will surely bring out the topics related to string, and ask the interviewee to perform some operation on a string. To extract a substring from a string is one of those questions. So, in this article, we shall go through some methods to extract a substring from a string in JavaScript language.
What is a string?
In programming, a string is a data type like integers and float that is formed using characters data type in combination. It is usually plain text that resides between two double quotations. For example, "I like JavaScript programming".
Using substring[] to extract a substring
Substring[] is a JavaScript function that extracts a portion of some entered string.
Here are some examples of using substring[] to extract a substring using the substring[] function.
Code:
The substring[] extracts a part of a string
let text = "The greatest glory in living lies not in never falling, but in rising every time we fall.";
let result = text.substring[1, 4]; //extracts the characters from the position 1 to 4
document.getElementById["demo"].innerHTML = result;
Output:
Run Code
Explaining the above program:
- Here, The variable text stores the string, and the result variable will store the extracted substring.
- The id attribute used is for defining the HTML element.
- In the line, let result = text.substring[1, 4], the function substring[] gets called, and passing parameters [1,4] will separate the characters from position 1 to 4 and store it in the result variable.
- Lastly, return the extracted substring stored in the result using the innerHTML method.
Extract a substring using the split[] function
Similar to the substring[], the split[] function also returns a part of a string. The string gets divided and the separation depends on the parameter we pass to the split[] function. The split[] function will split every character in the string if [""] is the parameter, and it will separate the words if [" "] is the parameter.
Code:
Program to extract a substring from a string
Extract the desired word from a string
The second word is:
let text = "How are you doing today?";
const myArray = text.split[" "];//The split[" "] function divides the string into an array of words
document.getElementById["demo"].innerHTML = myArray[2];//prints the the third word from the divided string
Output:
Run Code
Working of the program:
- Here, the variable text stores the string, and the id attribute will define the HTML element.
- In the line, const myArray = text.split[" "], the split[] function will separate the string stored in the variable text. Every word gets split and stored in the myArray array.
- Lastly, it will return the substring from the array using the innerHTML method.
Conclusion:
This article was about the methods for extracting a substring from a string. Handling strings and substrings are essential for everyone to create large applications. There are several methods and inbuilt functions in JavaScript for that purpose. There are two functions described in the above article for extracting a substring from a string. They are, substring[], split[].
JavaScript: The Definitive Guide
Take your understanding of JavaScript to the next level with this international best seller and build your mastery with detailed explanations and illuminating code examples.
We may earn a commission when you make a purchase, at no additional cost to you.
1. String slice[] Method
To get the first N
characters of a string in JavaScript, call the slice[]
method on the string, passing 0
as the first argument and N
as the second. For example, str.slice[0, 2]
returns a new string containing the first 2 characters of str
.
const str = 'Coding Beauty';
const first2 = str.slice[0, 2];
console.log[first2]; // Co
const first6 = str.slice[0, 6];
console.log[first6]; // Coding
const first8 = str.slice[0, 8];
console.log[first8]; // Coding B
The String
slice[]
method extracts the part of a string
between the start and end indexes, which are specified by the first and second arguments respectively. The substring between the indexes 0
and N
is a substring containing only the first N
string characters.
Note
Strings in JavaScript are immutable, and the slice[]
method returns a new string without modifying the original:
const str = 'Coding Beauty';
const first2 = str.slice[0, 2];
console.log[first2]; // Co
// Original not modified
console.log[str]; // Coding Beauty
2. String substring[] Method
To get the first N
characters of a string, we can also call the
substring[]
method on the string, passing 0
and N
as the first and second arguments respectively. For example, str.substring[0, 3]
returns a new string containing the first 3 characters of str
.
const str = 'Coding Beauty';
const first3 = str.substring[0, 3];
console.log[first3]; // Cod
const first5 = str.substring[0, 5];
console.log[first5]; // Codin
const first11 = str.substring[0, 11];
console.log[first11]; // Coding Beau
Like slice[]
, substring[]
returns the part of a string between the start and end indexes, which are specified by the first and second arguments respectively.
Note
substring[]
returns a new string without modifying the original:
const str = 'Coding Beauty';
const first3 = str.substring[0, 3];
console.log[first3]; // Cod
// Original not modified
console.log[str]; // Coding Beauty
Tip
The slice[]
and substring[]
methods work similarly for our scenario, but this isn’t always the case. Here’s one difference between them: substring[]
swaps its arguments if the first is greater than the second, but slice[]
returns an empty string [''
]:
const str = 'Coding Beauty';
const substr1 = str.substring[2, 0];
const substr2 = str.slice[2, 0];
// Equivalent to str.substring[0, 2]
console.log[substr1]; // Co
console.log[substr2]; // '' [empty string]
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more
expressive code.
Sign up and receive a free copy immediately.
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.