Finding the nth occurrence of a character in a string in javascript

docfree3

New Member
I am working on a javascript code to find the nth occurrence of a character in a string.Using the indexOf() function we are able to get the first occurrence of the character.now the challenge is to get the nth occurrence of the character.I was able to get the second third occurrence and so on using the code given below.\[code\] function myFunction() {<br/>var str="abcdefabcddesadfasddsfsd.";<br/><br/>var n=str.indexOf("d");<br/>document.write("First occurence " +n );<br/><br/>var n1=str.indexOf("d",parseInt(n+1));<br/>document.write("Second occurence " +n1 );<br/><br/>var n2=str.indexOf("d",parseInt(n1+1));<br/>document.write("Third occurence " +n2 );<br/><br/>var n3=str.indexOf("d",parseInt(n2+1));<br/>document.write("Fourth occurence " +n3) ;<br/><br/>var n4=str.indexOf("d",parseInt(n3+1));<br/>document.write("Fifth occurence " +n4 );<br/><br/>var n5=str.indexOf("d",parseInt(n4+1));<br/>document.write("Sixth occurence " +n5 );<br/><br/>// so on ..<br/>}\[/code\]

The results is given below
\[code\]First occurence 3 Second occurence 9 Third occurence 10 Fourth occurence 14 Fifth occurence 18 Sixth occurence 19\[/code\]I would like to generalize the script so that I am able to find the nth occurrence of the character as the above code requires us to repeat the script n times.Let me know if there is a better method or alternative to do the same.It would be nice if we just give the occurrence(at run time) to get the index of that character.The following are some of my questions
How do we do it in javascript?
Does any framework provide any functionality to do the same implementation in an easier way or what are the alternate methods to implement the same in other frameworks /languages?
Thank you
 
Back
Top