Skip to content

JavaScript split a sentence into words | Example code

  • by

Just use the split method to split a sentence into words in JavaScript. You can also use it for loop iteration. In both ways, you have to use the space option for separating normal sentences.

JavaScript split the sentence into words Example code

HTML example code:-

Using split method

It will return an array without space.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		var str = "This is an simple sentence.";
		var words = str.split(" ");
		console.log(words);

	</script> 
</body> 
</html>

Output: Return value be in Array.

JavaScript split a sentence into words array

Using for loop

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		var str = "This is an simple sentence.";
		var words = str.split(" ");
		for (var i = 0; i < words.length - 1; i++) {
			words[i] += " ";
		}
		console.log(words);

	</script> 
</body> 
</html>

Output: The result will be the same for both examples. But you can notice in this example have space after every word.

js split a sentence into words example

Do comment if you have any doubts and suggestions on this basic JS question-based topic and example code.

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 *