var string = ' abc def ghi '; var wordCount = 0; string.replace(/(^|\s)+[^\s]+/g, function(){wordCount++}); alert(wordCount);