Skip to content

Get word from string JavaScript | Extract a specific word example

Use split and some function or regex with word boundaries to find or Extract a specific word from a string in JavaScript.

Get word from string JavaScript Example

HTML example code: Match if word present in a given string.

Using split and some function

If a word is found then return true.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 
		var str = "Remove the last word.";

		function findWord(word, str) {
			return str.split(' ').some(function(w){return w === word})
		}

		console.log(findWord("last",str));
	</script> 
</body> 
</html>	

Using a regex with word boundaries:

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 
		var str = "Remove the last word.";

		function findWord(word, str) {
			return RegExp('\\b'+ word +'\\b').test(str)
		}

		console.log(findWord("last",str));
	</script> 
</body> 
</html>	

Output:

Get word from string JavaScript

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

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “Get word from string JavaScript | Extract a specific word example”

  1. ‘use strict’
    let str=’Remove the last word.’
    const findWord = (word) =>{
    return str.split(‘ ‘).some((w)=>w===word)===true?`The word ‘${word}’ is found`:`The word ‘${word}’ is not found`
    }
    console.log(findWord(‘last’))

Leave a Reply

Discover more from Tutorial

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

Continue reading