Use PHP functions in JavaScript

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 );
        }
    }
}
external links: original PHP docs | raw js source

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.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

No comments yet. Be the first!


Contribute a New function