Kam Kam - 1 year ago 77
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.

Answer Source

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;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download