Use PHP functions in JavaScript

JavaScript strrchr

Finds the last occurrence of a character in a string within another

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
function strrchr (haystack, needle) {
    // Finds the last occurrence of a character in a string within another  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/strrchr    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Jason Wong (http://carrot.org/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strrchr("Line 1\nLine 2\nLine 3", 10).substr(1)
    // *     returns 1: 'Line 3'    var pos = 0;
 
    if (typeof needle !== 'string') {
        needle = String.fromCharCode(parseInt(needle, 10));
    }    needle = needle.charAt(0);
    pos = haystack.lastIndexOf(needle);
    if (pos === -1) {
        return false;
    } 
    return haystack.substr(pos);
}
external links: original PHP docs | raw js source

Examples

Running

1
strrchr("Line 1\nLine 2\nLine 3", 10).substr(1)

Should return

1
'Line 3'

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 strrchr 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
Brett Zamir
29 May '09 Permalink

q  Thanks, Jason...Fixed in SVN (using needle.charAt(0)).

Gravatar
Jason Wong
29 May '09 Permalink

q  This function seems can not work properly in IE but works fine in firefox. For example, strrchr("java.js","."), it will always return false. The reason is that the needle is currently a string, however, needle[0] is undefined.
Good Luck.


Contribute a New function