Skip to content

Instantly share code, notes, and snippets.

@trinhvanminh
Last active July 5, 2023 07:19
Show Gist options
  • Save trinhvanminh/5b5373f9ad2c349b587806b642308b22 to your computer and use it in GitHub Desktop.
Save trinhvanminh/5b5373f9ad2c349b587806b642308b22 to your computer and use it in GitHub Desktop.
python string format method for javascript
// 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