Created
June 4, 2013 01:51
-
-
Save TravelingTechGuy/5703022 to your computer and use it in GitHub Desktop.
String manipulation functions (and polyfills) - to be used with RequireJS
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
"use strict"; | |
//String functions | |
define([], function() { | |
var addFunctionToString = function(name, value) { | |
if(!String.prototype.hasOwnProperty(name)) { | |
Object.defineProperty(String.prototype, name, { | |
enumerable: false, | |
configurable: false, | |
writable: false, | |
value: value | |
}); | |
} | |
}; | |
// Format a string: "Hello {0}, it's {1} o'clock".format("world", 5) -> hello world, it's 5 o'clock | |
addFunctionToString('format', function() { | |
var args = arguments; | |
return this.replace(/{(\d+)}/g, function(match, number) { | |
return (typeof args[number] !== 'undefined') ? args[number] : match; | |
}); | |
}); | |
// Ellipsise a long string | |
// toLength is the max length of the result | |
// where is one of ['front','middle','end'] -- default is 'end' | |
// ellipsis is the character used -- default is ... | |
addFunctionToString('ellipsise', function(toLength, where, ellipsis) { | |
if (toLength < 1 || this.length < toLength) return this.toString(); | |
ellipsis = ellipsis || '\u2026'; | |
switch (where) { | |
case 'front': | |
return ellipsis + this.substr(this.length - toLength); | |
break; | |
case 'middle': | |
return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2); | |
break; | |
case 'end': | |
default: | |
return this.substr(0, toLength) + ellipsis; | |
break; | |
} | |
}); | |
// Returns true if a string starts with the search string | |
// optional: search start position | |
addFunctionToString('startsWith', function(searchString, position) { | |
position = position || 0; | |
return this.indexOf(searchString, position) === position; | |
}); | |
// Returns true if a string ends with the search string | |
// optional: search end position | |
addFunctionToString('endsWith', function(searchString, position) { | |
position = position || this.length; | |
position = position - searchString.length; | |
return this.lastIndexOf(searchString) === position; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment