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: 909.322 // 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); } |
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.

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