Get the last word from string JavaScript | Example code

Use Regular expression or with replace and split method to get the the last word from string JavaScript. It’s not only way to get last word from string you can use split or inbuilt lastIndexof with substring method.

Get the last word from string JavaScript example code

HTML example code:-

Regular expression

A strips all punctuation and returns the last word of a string, hyphens (-) aren’t stripped, add the hyphen to the regex to strip it as well.

Split method

Use words with n word length.

Using indexof and substring method

inbuilt JavaScript functions for last word.

Output: Result will be same because string content is same.

Get the last word from string JavaScript

Do comment if you have any doubts and suggestions on this JS string topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.