Created
August 22, 2016 09:22
-
-
Save aloha1003/9aae6809c96d5929b82a38e71c4f7cff to your computer and use it in GitHub Desktop.
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
String.prototype.format = String.prototype.f = function() { | |
var s = this, | |
i = arguments.length; | |
var compareStr = ''; | |
var map = {}; | |
if ( (arguments.length == 1) && (typeof arguments[0] === 'object')) { | |
for (var prop in arguments[0]) { | |
key = prop; | |
compareStr += key+'|'; | |
map['{'+key+'}'] = arguments[0][prop]; | |
} | |
} else { | |
while (i--) { | |
key = i; | |
compareStr += key+'|'; | |
map['{'+key+'}'] = arguments[i]; | |
} | |
} | |
var regExp = new RegExp("{("+compareStr+")}", "g"); | |
s = s.replace(regExp, function (matched){ | |
return map[matched]; | |
}); | |
return s; | |
}; | |
var test = "Hello {name}, {world}"; | |
var test2 =" Hello {0}, {1}"; | |
console.log(test.format({"name":"A", "world" : "B"})); | |
console.log(test2.format("C","D")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment