How can you search words in a string with its occurance in javascript?

If I have a string "The combination of JavaScript and CSS can create stunning web applications for the project.", from this string, need to count the occurance of the word "the" with case insensitive.


solution

To search for words in a string with its occurrence in JavaScript, you can use the `match()` method in combination with a regular expression. Here's an example:

const str = "The combination of JavaScript and CSS can create stunning web applications for the project.";
const searchWord = "the";
const regex = new RegExp(searchWord, "gi");
const matches = str.match(regex);
console.log(`The word "${searchWord}" was found ${matches.length} times in the string.`);

In this example, we create a string `str` and a search word `searchWord`. We then create a regular expression using the `RegExp` constructor, passing in the search word and the `"gi"` flags. The `"g"` flag stands for global, meaning the regular expression will match all occurrences of the search word in the string. The `"i"` flag stands for case-insensitive, so the regular expression will match the search word regardless of its case.

We then call the `match()` method on the string, passing in the regular expression as an argument. This returns an array of all matches found in the string. We can then log the number of matches found using the `length` property of the array.

Note that this method will only match whole words, so if the search word appears as part of a larger word (e.g. "there"), it will not be counted as a match. If you want to match partial words, you could modify the regular expression accordingly.

Published on: 03-May-2023