In this blog post you’ll learn how to extract the first and last characters of the string using JavaScript. We’ll see 5 different approaches to extract the first and last character from a string.
JavaScript method used:
CharAt()
slice()
substring()
substr()
With string[].
Approach 1: With CharAt() Method.
The CharAt method returns a character at a specific index position.
See below example:
JavaScript
let string = "Hello welcome to maketechstuff.com";
console.log("First Charcter: ", string.charAt(0));
console.log("Last Charcter: ", string.charAt(string.length - 1));
// Output:
// First Charcter: H
// Last Charcter: m
Approach 2: With slice() Method.
Slice method returns the selected element.
See below code:
JavaScript
let string = "Hello welcome to maketechstuff.com";
console.log("First Charcter: ", string.slice(0, 1));
console.log("First Charcter: ", string.slice(string.length-1));
Output:
// First Charcter: H
// Last Charcter: m
Approach 3: With substring() Method.
Substring returns the characters between two index positions.
See below code.
JavaScript
let string = "Hello welcome to maketechstuff.com";
console.log("First Charcter: ", string.substring(0, 1));
console.log("First Charcter: ", string.substring(string.length-1));
Output:
// First Charcter: H
// Last Charcter: m
Approach 4: with substr() Method.
Substr method return characters start from specific index position upto defined length.
See below code.
JavaScript
let string = "Hello welcome to maketechstuff.com";
console.log("First Charcter: ", string.substr(0, 1));
console.log("First Charcter: ", string.substr(-1));
Output:
// First Charcter: H
// Last Charcter: m
Approach 5: with string[].
In this approach we directly extract the character with index value.
JavaScript
let string = "Hello welcome to maketechstuff.com";
console.log("First Charcter: ", string[0]);
console.log("First Charcter: ", string[string.length - 1]);
// Output:
// First Charcter: H
// Last Charcter: m
So that's how you can extract the first and last character from the string. Feel free to ask any questions or suggestions in the comment section.
- Extract the numers from a string using JavaScript.
- Check if string is number using JavaScript.
- Count the words present in the string using JavaScript.
- Count the characters present in the string using JavaScript.
- Split the string into an character array using JavaScript.
- Split the string into an array of words using JavaScript.
- Replace multiple spaces between words to single spaces in input field value.
Share your thoughts.