5 Easy Ways To Get First and Last Character From String Using JavaScript.

0

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.


get first and last character from the 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.


You may like:


Tags

Post a Comment

0Comments

Share your thoughts.

Post a Comment (0)
To Top