Last active
July 5, 2023 07:19
-
-
Save trinhvanminh/5b5373f9ad2c349b587806b642308b22 to your computer and use it in GitHub Desktop.
python string format method for javascript
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
// function ---------------------------------------------------------- | |
// ex: stringFormat("its like python{0} format", 3) ==> its like python3 format | |
export function stringFormat(string) { | |
[...Array(arguments.length)].forEach( | |
(_, i) => (string = string.replace("{" + (i - 1) + "}", arguments[i])) | |
); | |
return string; | |
} | |
// add to String prototype ------------------------------------------- | |
// ex: "its like python{0} format".format(3) ==> its like python3 format | |
const buildStringFormat = () => { | |
String.prototype.format = function () { | |
var a = this; | |
for (var k in arguments) { | |
a = a.replace(new RegExp('\\{' + k + '\\}', 'g'), arguments[k]); | |
} | |
return a; | |
}; | |
}; | |
const stringExtensions = () => { | |
buildStringFormat(); | |
}; | |
export stringExtensions; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment