Use PHP functions in JavaScript

JavaScript stripos

Finds position of first occurrence of a string within another, case insensitive

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
function stripos (f_haystack, f_needle, f_offset) {
    // Finds position of first occurrence of a string within another, case insensitive  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/stripos    // +     original by: Martijn Wieringa
    // +      revised by: Onno Marsman
    // *         example 1: stripos('ABC', 'a');
    // *         returns 1: 0
    var haystack = (f_haystack + '').toLowerCase();    var needle = (f_needle + '').toLowerCase();
    var index = 0;
 
    if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
        return index;    }
    return false;
}
external links: original PHP docs | raw js source

Examples

Running

1
stripos('ABC', 'a');

Should return

1
 

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 stripos 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
Kevin van Zonneveld
6 Oct '08 Permalink

q  @ Onno Marsman: Processed. Thank you!

Gravatar
Onno Marsman
4 Oct '08 Permalink

q  Improved to accept things other than strings. Also "if(f_offset == undefined) {" seemed useless since indexOf accepts undefined as a 0 anyway. Also changed > -1 to !== -1, to increase performance a tiny bit.

[CODE="Javascript"]
function stripos ( f_haystack, f_needle, f_offset ) {
var haystack = (f_haystack+'').toLowerCase();
var needle = (f_needle+'').toLowerCase();
var index = 0;

if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
return index;
}
return false;
}
[/CODE]

Gravatar
Kevin van Zonneveld
7 Mar '08 Permalink

q  @ Thiago Mata: Thanks alot, I've added the function!

Gravatar
call_user_func_array
7 Mar '08 Permalink

q  [CODE="Javascript"]
/**
* @author Thiago Mata
* @date 07/03/2008
* @param callback strFunctionName
* @param array arrParam
* @return mixer
* @url thiagomata.blog.com
*/
function call_user_func_array( strFunctionName , arrParam )
{
var strCommand = "";
var i;

strCommand += "return " + strFunctionName + "(";
for( i = 0; i < arrParam.length; ++i )
{
strCommand += "arrParam[" + i + "]" ;
if( ( i + 1 ) != arrParam.length )
{
strCommand += ",";
}
}
strCommand += ")";
var oFunction = new Function( "arrParam" , strCommand );
return oFunction( arrParam );
}
[/CODE]


Contribute a New function