user1712095
user1712095

Reputation: 197

counting words that begin with a given substring

I am trying to find the count of words in a given string that start with a particular substring, without prototype:

myString="cat car cab. came, corn ";
substring = "ca";
count =0;
if (myString.match(substring))
   count++;

return count;

My expected result is 4.

Upvotes: 1

Views: 89

Answers (3)

user1712095
user1712095

Reputation: 197

Will use Regex to match words in string, Regex will result an array of matched words, as an Example:

string = "car cat caw ctt" 
subString = "ca"

string.match(new RegExp('\\b' + subString, 'g'))  // will reult ["ca", "ca", "ca"]

and in case no match will return null and that's why we have || to return an empty array

a = null || [] // this will return []

and for the resulted array will check the length and return.

  function countWordsBeginningWith(subString, myString){

     var count = (myString.match(new RegExp('\\b' + subString, 'g')) || 
     []).length;

    return count;       
}

Upvotes: 0

Tushar
Tushar

Reputation: 87203

You can use regex:

var myString = 'cat car cab. came, corn ';
alert(myString.match(/\s?(ca\w*)/g).length)

Upvotes: 2

Amit
Amit

Reputation: 46323

You can use match with a global regex and examine the length of the returned :array

function countWordsWithSubstring(sentence, substring) {
  var matches = sentence.match(new RegExp('\\b' + substring, 'g'));
  return matches ? matches.length : 0;
}
                                 
var myString="cacat acaacacar cab. came, corn ";
alert(countWordsWithSubstring(myString, 'ca'));

Upvotes: 1

Related Questions