Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To get last character of string in react js, use substring() method to extracts last character from string. You have to only pass starting and ending postion of string so for last character pass text.length - 1 as parameter it will return last character of string.

Let’s see short example to use substring() to get last character from string.

text.substring(text.length - 1);

Today, I’m going to show you How do I get last character of string in react js, as above mentioned, I’m going to use the above-mentioned substring() method.

Let’s start today’s tutorial how do you get last character of string in react js?

React JS get last character of string example using substring()

Here, we will take string state with some data and use substring() method to get last char of string.

import React, { useState, useEffect } from "react";
export default function App() {
  const [str, setStr] = useState("Infinitbility");

  useEffect(() => {
    setStr(str.substring(str.length - 1))
  }, []);

  return (
    <div className="App">
      <p>{str}</p>
    </div>
  );
}

Output

React JS get last character of string example using index

Here, we will take string state with some data and use index method to get last char of string.

import React, { useState, useEffect } from "react";
export default function App() {
  const [str, setStr] = useState("Infinitbility");

  useEffect(() => {
    setStr(str[str.length - 1])
  }, []);

  return (
    <div className="App">
      <p>{str}</p>
    </div>
  );
}

Output

React JS get last character of string example using charAt()

Here, we will take string state with some data and use charAt() method to get last char of string.

import React, { useState, useEffect } from "react";
export default function App() {
  const [str, setStr] = useState("Infinitbility");

  useEffect(() => {
    setStr(str.charAt(str.length - 1))
  }, []);

  return (
    <div className="App">
      <p>{str}</p>
    </div>
  );
}

Output

I hope it helps you, All the best đź‘Ť.