A Flash Developer Resource Site

Results 1 to 2 of 2

Thread: nth index of character

  1. #1
    Senior Member Boombanguk's Avatar
    Join Date
    Jun 2000
    Posts
    1,194

    nth index of character

    Hi,

    I know you can use lastindexOf and indexof to find the place of where a string is in another string, but what if i want to find the 2nd or the 3rd position or a string?

  2. #2
    Junior Member
    Join Date
    Aug 2005
    Posts
    27
    The second parameter to indexOf specifies the starting point of the search. You can use a recursive call to a function that searches the string from the next starting point:

    Code:
    function getIndex(searchMe, searchFor, count, startFrom) {
    	//Search the string, if startFrom is undefined, use 0 as default
    	var index = searchMe.indexOf(searchFor, startFrom ? startFrom : 0);
    	//If count > 1, call this function again starting at index+1
    	return (count > 1) ? getIndex(searchMe, searchFor, count-1, index+1) : index;
    }
    
    //Try it out:
    var teststring = "testtesttest";
    var findstring = "test";
    
    //Get the 1st instance, returns 0 (the index of the 1st character)
    trace(getIndex(teststring, findstring, 1));
    
    //Get the 2nd instance, returns 4
    trace(getIndex(teststring, findstring, 2));
    
    //Get the 3rd instance, returns 8
    trace(getIndex(teststring, findstring, 3));
    
    //Get the 4th instance, returns -1 (not found)
    trace(getIndex(teststring, findstring, 4));

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center