Kam Kam - 1 month ago 5
Javascript Question

Finding word occurences in a string

var temp = "This is a string.";
var findtext="is";
var count = (temp.match("/"+findtext+"/g") || []).length;
console.log(count);


I have made a java script function which gets the user string from a text area. It take another perimeter for the word which is to be found from the entered text. It gives me error as i am not able to get the number of occurrence for the word to be found from the string.

Answer

You'd want to use the RegExp constructor, and a word boundary to match whole words so as to not match the is in This etc

var temp     = "This is a string.";
var findtext = "is";
var regex    = new RegExp('\\b'+ findtext+'\\b', 'g');
var count    = (temp.match(regex) || []).length;

console.log(count); 

Comments