Skip to content

Get the last word from string JavaScript | Example code

  • by

Use Regular expression or with replace and split method to get the last word from string JavaScript. It’s not the only way to get the last word from the string you can use split or inbuilt lastIndexof with the 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.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 

		function lastWord(words) {
			let n = words.replace(/[\[\]?.,\/#!$%\^&\*;:{}=\\|_~()]/g, "").split(" ");
			return n[n.length - 1];
		}

		// Test case
		var str = "Get the last word.";
		console.log(lastWord(str));
	</script> 
</body> 
</html>		

Split method

Use words with n word length.

<script> 
		function getLastWord(words) {
			var n = words.split(" ");
			return n[n.length - 1];

		}
		// Test case
		var str = "Get the last word.";
		console.log(getLastWord(str));
</script> 

Using indexof and substring method

inbuilt JavaScript functions for last word.

<script> 
		function getLastWord(words) {
			var n = words.lastIndexOf(" ");

			var res = words.substring(n);
			return res;
		}
		// Test case
		var str = "Get the last word.";
		console.log(getLastWord(str));
</script> 

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: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading