I want to count the number of occurrences of a string at the end of the string. I want it to ignore occurrences that are not at the end and I want it to return zero if there are none.
terminal string to find: "-1"
e.g. string = 1
// 0
e.g. string = 1-1
// 1
e.g. string = 1-1-1
// 2
e.g. string = 1-2-1
// 1
e.g. string = 1-2-1-2-1
// 1
e.g. string = 2-1-1-1-1
// 4
e.g. string = 1-1-2
// 0
I want it to count all of the occurrences at the end of the string, not just the occurrences anywhere in the string.
I tried:
var occurrences = string.match(/(-1)*$/).length;
I have a JS Fiddle here: JS Fiddle
It returns "2", no matter what my string.
You need to work on the first element of the returned array:
Find the length of first element which is the matched string of
"-1"
at the end and divide by 2 since the string"-1"
is of length2
.To quote from MDN String.prototype.match():