Sunday, October 21, 2012

JavaScript SecondIndexOf or (x)indexOf

The JavaScript indexOf() and lastIndexOf() methods return the position of the first and last occurrence of a specified value in a string

You can learn more about them here

These can be very usefull, but what if you want the Second indexOf() to get the second occurrence of a specified value in a string. There is no standard JavaScript method for this, so I made my own one;

 function SecondIndexOf(Val, Str)  
 {  
   var Fst = Str.indexOf(Val);  
   var Snd = Str.indexOf(Val, Fst+1)  
   return Snd  
 }  

But why stop there, what if you want the third or fourth indexOf()
The following function lets you specify which occurrence of the specified value to find in the string;

 function xIndexOf(Val, Str, x)  
 {  
   if (x <= (Str.split(Val).length - 1)) {  
     Ot = Str.indexOf(Val);  
     if (x > 1) { for (var i = 1; i < x; i++) { var Ot = Str.indexOf(Val, Ot + 1) } }  
     return Ot;  
   } else { alert(Val + " Occurs less than " + x + " times"); return 0 }  
 }  

Here is an egsample of how you can use this;

   var PicPath = "/somedirectory/pics/";  
   var AppPath = picpath.substring(0, xIndexOf('/', PicPath, 2) + 1);  

Let me know if you found this usefull, or can recommend any enchancments.

8 comments:

  1. I am not a practitioner of javasript and I find this example difficult to understand but the link in w3schools is very understandable.

    I think, what IndexOf does is search the string where it match and return the first character location of the parameter used.

    Kyle Smith on Semphi

    ReplyDelete
  2. Hi Kyle

    Thanks for your comment, your understanding of IndexOf is correct.

    The reason that I linked to w3schools is that my post is not about explaining how IndexOf works, but rather it’s about extending it to get the second or even third instance of a parameter in a string, as IndexOf only returns the first instance.

    ReplyDelete
  3. Thanks for you, It's work 100% for me.

    ReplyDelete
    Replies
    1. Saya senang bisa membantu (I am glad I could help)

      Delete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. Great! Very useful. Thanks.

    ReplyDelete
  6. mas bos mau tanya ne kira2 bisa ngga edit massal code dalam blogspot ? jadi semisal pada semua artikel ada link c.com mau saya ganti d.com dengan menggunakan code diatas ?

    ReplyDelete
    Replies
    1. Please keep your comment in English as this is an English blog. With regards to your question, this code will not do a bulk find and replace on Blogspot, and I do not know how you would do that.

      Delete