Javascript: How to find all occurences of a string in another string
In Javascript, the indexOf() method will find the index of first occurence of a string in another string.
eg
txt = "You are like like me"
str = "ke"
ind = txt.indexOf(str)
But there is no native method in JS for finding all the occurences of a string.
Here is a function to do that.
function allindices(txt,str)
{
var lentxt = txt.length
var lenstr = str.length
var j = 0
var indices = new Array()
indices[0] = -1
if (lenstr > lentxt)
return indices;
var i = 0
while(i < lentxt - 1)
{
ind = txt.slice(i).indexOf(str)
//'ind' is the position of 'str' in the current slice
if (ind == -1)
{
return indices
}
else
{
i = ind+i //Shift the index
for(k in indices)
{
if (i == indices[k])
break
else if (k+1 == indices.length)
{
indices[j] = i
j = j + 1
}
}
}
i = i + 1
}
return indices
}
This function can be used as follows:
arr = allindices(txt,str)
if (arr[0] != -1) \\Print all indices
{
for(var i = 0;i < arr.length;i++)
{
document.write(arr[i])
}
}
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home