javascript find occurrence in string

indexOf - return index of first occurrence:

'Blue Whale'.indexOf('Blue');     // returns  0
'Blue Whale'.indexOf('Blute');    // returns -1
'Blue Whale'.indexOf('Whale', 0); // returns  5
'Blue Whale'.indexOf('Whale', 5); // returns  5
'Blue Whale'.indexOf('Whale', 7); // returns -1
'Blue Whale'.indexOf('');         // returns  0
'Blue Whale'.indexOf('', 9);      // returns  9
'Blue Whale'.indexOf('', 10);     // returns 10
'Blue Whale'.indexOf('', 11);     // returns 10
'Blue Whale'.indexOf('blue'); // returns -1 - Case sensitive
 
var copyright = 'site.com. All rights reserved. | Privacy Policy';
var copyright_cut = copyright.substring(0, copyright.indexOf('reserved')+8); // copyright_cut = 'site.com. All rights reserved'

lastIndexOf - return index of last occurrence:

'canal'.lastIndexOf('a');     // returns 3
'canal'.lastIndexOf('a', 2);  // returns 1
'canal'.lastIndexOf('a', 0);  // returns -1
'canal'.lastIndexOf('x');     // returns -1
'canal'.lastIndexOf('c', -5); // returns 0
'canal'.lastIndexOf('c', 0);  // returns 0
'canal'.lastIndexOf('');      // returns 5
'canal'.lastIndexOf('', 2);   // returns 2
'Blue Whale, Killer Whale'.lastIndexOf('blue'); // returns -1 - Case sensitive

Leave a Reply

Your email address will not be published. Required fields are marked *