Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To get last word of string in react native, use split(" ") method with strArr.length - 1 index value it will return last word from string. You have to only pass " " in split() method.

Let’s see short example to use split(" ") with with strArr.length - 1 index to get last word from string.

let strArr = string.split(" ");
strArr[strArr.length - 1];

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

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

React native get last word of string example

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

import React, { useState, useEffect } from "react";
import { Text, View } from 'react-native';

export default function App() {
  const [str, setStr] = useState("Welcome to infinitbility");

  useEffect(() => {
    console.log(getLastWord(str))
  }, []);

  const getLastWord = (str) => {
    let strArr = str.split(" ");

    if(strArr.length > 0){
      return strArr[strArr.length - 1];
    }

    return "";
  }

  return (
    <View>
      <Text>{getLastWord(str)}</Text>
    </View>
  );
}

***TIP: Before acceing any array value using index check length greater than 0 or not ***

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

Output

React native get last word of string example
React native get last word of string example

Try it yourself