Skip to content

Get the first word of string JavaScript | Example code

  • by

Use split method with 0 indexes to get the only first word of string in JavaScript. The split method returns an array, so you can easily get the first element.

> "hey there".split(" ")[0]
"hey"

Get the first word of string JavaScript example

HTML example code:

You need to split the string by space and get only 0 index values.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>

		var str = "Hello world!";
		var res = str.split(' ')[0];

		console.log(res);
	</script> 
</body> 
</html>	

Output:

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

Your email address will not be published. Required fields are marked *