JavaScript stristr
Finds first occurrence of a string within another, case insensitive
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 25 | function stristr (haystack, needle, bool) { // Finds first occurrence of a string within another, case insensitive // // version: 1008.1718 // discuss at: http://phpjs.org/functions/stristr // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfxied by: Onno Marsman // * example 1: stristr('Kevin van Zonneveld', 'Van'); // * returns 1: 'van Zonneveld' // * example 2: stristr('Kevin van Zonneveld', 'VAN', true); // * returns 2: 'Kevin ' var pos = 0; haystack += ''; pos = haystack.toLowerCase().indexOf( (needle+'').toLowerCase() ); if (pos == -1){ return false; } else{ if (bool) { return haystack.substr( 0, pos ); } else{ return haystack.slice( pos ); } } } |
Examples
» Example 1
Running
1 | stristr('Kevin van Zonneveld', 'Van'); |
Should return
1 | 'van Zonneveld' |
» Example 2
Running
1 | stristr('Kevin van Zonneveld', 'VAN', true); |
Should return
1 | 'Kevin ' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have stristr goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: @HalfWinter, Paulo Freitas, Andros Peña Romo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>