how to find the last word of a string in javascript

How to Find the Last Word of a String in JavaScript

If you're working with strings in JavaScript, you might need to find the last word of a string for various reasons. Here are a few ways you can achieve this:

Method 1: Using Split and Pop

You can split the string into an array of words using the split method and then use the pop method to get the last word of the array:


const str = "This is a sample string";
const words = str.split(" ");
const lastWord = words.pop();
console.log(lastWord); // Output: "string"

Here, we first defined a string str. Then, we used the split method to split the string into an array of words using the space character as a separator. We stored this array in the words variable. Finally, we used the pop method to get the last word of the array and stored it in the lastWord variable.

Method 2: Using LastIndexOf and Substring

You can also use the lastIndexOf method to find the index of the last space character in the string and then use the substring method to extract the last word:


const str = "This is a sample string";
const lastIndex = str.lastIndexOf(" ");
const lastWord = str.substring(lastIndex + 1);
console.log(lastWord); // Output: "string"

In this method, we first defined a string str. We then used the lastIndexOf method to find the index of the last space character in the string and stored it in the lastIndex variable. Finally, we used the substring method to extract the last word from the string starting from the index after the last space character and stored it in the lastWord variable.

Method 3: Using Regular Expression

You can also use regular expressions to find the last word of a string:


const str = "This is a sample string";
const lastWord = str.match(/\w+$/)[0];
console.log(lastWord); // Output: "string"

In this method, we first defined a string str. We then used the match method to match the last word of the string using the regular expression /\w+$/, which matches any word characters (letters, digits, and underscores) at the end of the string. The match method returns an array of all matches, so we used [0] to get the first (and only) match, which is the last word of the string.

These are a few ways you can find the last word of a string in JavaScript. Choose the one that suits your need and coding style.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe