Use PHP functions in JavaScript

JavaScript strstr

Finds first occurrence of a string within another

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
30
function strstr (haystack, needle, bool) {
    // Finds first occurrence of a string within another  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/strstr    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strstr('Kevin van Zonneveld', 'van');
    // *     returns 1: 'van Zonneveld'    // *     example 2: strstr('Kevin van Zonneveld', 'van', true);
    // *     returns 2: 'Kevin '
    // *     example 3: strstr('name@example.com', '@');
    // *     returns 3: '@example.com'
    // *     example 4: strstr('name@example.com', '@', true);    // *     returns 4: 'name'
    var pos = 0;
    
    haystack += '';
    pos = haystack.indexOf( needle );    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
strstr('Kevin van Zonneveld', 'van');

Should return

1
'van Zonneveld'

» Example 2

Running

1
strstr('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 strstr 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

Gravatar
Val Che
Apr 5th Permalink

q  Thanks man! Works fine for me :-)


Contribute a New function