Created
April 2, 2014 22:16
-
-
Save kadimi/9944366 to your computer and use it in GitHub Desktop.
Replace the last occurence of a string, useful if you want to replace the last comma with " and"...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Replace the last occurence of a string, useful if you want to replace the last comma with " and"... | |
* | |
* @param str needle The string to search | |
* @param str replacement The replacement string | |
* @param str str The subject | |
* @return str The new string | |
*/ | |
function str_replace_last(needle, replacement, str) { | |
var needle_index = str.lastIndexOf(needle); | |
if (needle_index < 0) { | |
return str; | |
} else { | |
return str.substr(0, needle_index) + replacement + str.substr(needle_index + needle.length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment