Created
February 3, 2014 17:57
-
-
Save ox/8788878 to your computer and use it in GitHub Desktop.
angular filter that replaces a suffix with another
This file contains hidden or 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 file pointed at | |
angular.module('vendorApp') | |
.filter('replace', function () { | |
'use strict'; | |
// check if str ends with suffix | |
function endsWith(str, suffix) { | |
return str.indexOf(suffix, str.length - suffix.length) !== -1; | |
} | |
// take suffix off of str if str ends with suffix | |
// return the string otherwise | |
function trimSuffix(str, suffix) { | |
if (endsWith(str, suffix)) { | |
return str.slice(0, -(suffix.length)); | |
} else { | |
return str; | |
} | |
} | |
// 'path/to/img.jpg' | replace:'img.jpg':'orig_img.jpg' | |
// replace defaults to 'photo.jpg' | |
// withStr defaults to 'original_photo.jpg' | |
return function (imagePath, replace, withStr) { | |
if (!imagePath) { return imagePath; } | |
replace = replace || 'photo.jpg'; | |
withStr = withStr || 'original_photo.jpg'; | |
// '#'s are added to the ends of image paths to trigger | |
// ngSrc to reload the image. This strips them off. | |
while (endsWith(imagePath, '#')) { | |
imagePath = trimSuffix(imagePath, '#'); | |
} | |
if (!endsWith(imagePath, replace)) { | |
return imagePath; | |
} | |
return trimSuffix(imagePath, replace) + withStr; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment