Kam Kam - 9 days ago 4
Javascript Question

Finding word occurences in a string

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

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.


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;