Skip to content

Instantly share code, notes, and snippets.

@kadimi
Created April 2, 2014 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kadimi/9944366 to your computer and use it in GitHub Desktop.
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"...
/**
* 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