tomhoppe.com

Racing, Web Development, Photography, and Beer...Stuff that matters.

Monday, January 5, 2009

How many times does "x" occur in a string?

Had to figure out how many times a single characted occured in a string today. Found a nice clean way to do that instead of running a loop. Remove all the instances of that letter or character in the string, and the subtract that from the original length of the string. Viola.

You can also adapt this to multi character strings by dividing the result by the amount of chars in your search string. If you look for "asdf" in "1234asdf1234asdf1234asdf", you will remove 12 characters. Divide that by 4, and you have found "asdf" three times. Two examples below where the result is 3

str = 1234x1234x1234x;
str.length - str.replace(/x/gi,'').length;
str = 1234asdf1234asdf1234asdf
(str.length - str.replace(/xxxx/gi,'').length)/4

Labels: ,

0 Comments:

Post a Comment

<< Home