JavaScript Equivalent for PHP's substr_count()


This is the javascript equivalent of the PHP function substr_count(). Which is a function that counts the number of times a substring occurs in a string. This will enable you to use this PHP excusive function in your JavaScript codes. To use this function please review "How to Use" and the example usage of the function below.

How to Use

To use this function simply add the function into the bottom of your existing JavaScript code and call the function using the required parameters. Please consult the parameters list below for parameters and there desciptions.

JavaScript Function

function substr_count(string,substring,start,length)
{
 var c = 0;
 if(start) { string = string.substr(start); }
 if(length) { string = string.substr(0,length); }
 for (var i=0;i<string.length;i++)
 {
  if(substring == string.substr(i,substring.length))
  c++;
 }
 return c;
}

Syntax

substr_count(string,substring,start,length);

Parameter Desciption

ParameterNecessityDescription
stringRequired.Specifies the string to check.
substringRequired.Specifies the string to search for.
startOptional.Specifies where in string to start searching.
lengthOptional.Specifies the length of the search.

Example Usage of substr_count()

Example 1:
function call:
substr_count('Your apples are my apples.','apples');
results:

Example 2:
function call:
substr_count('Your apples are my apples.','apples',0,11);
results:

Developer

This function was developed by Sean Gallagher. He is a website designer, developer and search engine optimizer who currently runs a web development, design and SEO company based out of the Pittsburgh area. To visit his company websites go to Pittsburgh SEO, Pittsburgh Website Design, Atlanta Website Design.

License

This function is released under the free software licenced GNU General Public License.

Copyright © 2008 Sean Gallagher

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see .