This article explains “ How to retrieve partial characters from a string’ ‘ in JavaScript .
How can I partially retrieve characters from a string?
There are methods to partially retrieve characters from a string, such as substring, slice, substr, and charAt.
substring, slice, substr, charAt to retrieve characters partially from a string
Use , substring
, slice
, substr
to partially extract characters from a string .charAt
method name | value to specify | character to get |
---|---|---|
substring(start [,end]) | start, end | Characters from start to end-1 |
slice(start [,end]) | start, end | Characters from start to end-1 |
substr(start [,length]) | start, length | length characters from start |
charAt(index) | index | character corresponding to index |
To get some characters from a string range (start to end), use the substring / slice method .
string.substring(start [,end]);
string.slice(strat [,end]);
If you want to extract by starting position and number of characters, use the substr method .
string.substr(start, length);
Used to retrieve a single character corresponding to the index of a string.
string.chartAt(index);
Below is a sample that partially extracts characters from a string.
let str = "JavaScript";
console.log(str.substring(0,4)); // "Java"
console.log(str.slice(2,6)); // "vaSc"
console.log(str.substr(3,5)); // "aScri"
console.log(str.charAt(5)); // "S"
Summary of “How to partially retrieve characters from a string”
The following is a summary of how to partially retrieve characters from a string .
- substring is used to get part of a string and specifies the start and end index.
- slice is used to get a part of a string and specifies the start and end index.
- substr is used to get part of a string and specifies start and length.
- charAt is used to get the character corresponding to the index of a string.
method name | value to specify | character to get |
---|---|---|
substring(start [,end]) | start, end | Characters from start to end-1 |
slice(start [,end]) | start, end | Characters from start to end-1 |
substr(start [,length]) | start, length | length characters from start |
charAt(index) | index | character corresponding to index |
It was helpful to be able to clearly explain the differences between the two.
Comments