Last Updated : 03 Dec, 2024
Here are the various methods to get the first three characters of a string in JavcaScript
1. Using String.slice() MethodThe slice() method is one of the most commonly used and versatile methods to extract a part of a string. It allows you to specify the start and end positions for slicing the string.
JavaScript
let s = 'Hello, World!';
let res = s.slice(0, 3);
console.log(res);
The substr() method is another option for extracting parts of a string. It allows you to specify the starting index and the length of the substring you want to extract.
JavaScript
let s = 'Hello, World!';
let res = s.substr(0, 3);
console.log(res);
The substring() method is similar to slice(), but with slightly different behavior. It takes two arguments: the starting index and the ending index, and extracts the characters between them.
JavaScript
let s = 'Hello, World!';
let res = s.substring(0, 3);
console.log(res);
In JavaScript, strings can be treated as arrays of characters, so you can also use the slice() method on a string converted to an array to get the first three characters.
JavaScript
let s = 'Hello, World!';
let res = [...s].slice(0, 3).join('');
console.log(res);
If you want to manually retrieve the first three characters, you can iterate over the string and extract the characters at the specific indexes.
JavaScript
let s = 'Hello, World!';
let res = '';
for (let i = 0; i < 3; i++) {
res += s[i];
}
console.log(res);
When you need a method similar to slice(), but with different handling of arguments.
Slightly less common than slice(), but still widely used. Array.slice() with String Conversion When you want to treat the string as an array and need more flexibility. More complex and less efficient, but can be useful for array-like operations. Looping with String Indexing When you want to manually control each character in the string. Least efficient, but useful for custom scenarios.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4