Greasy Fork is available in English.

string format

Format a string with '{0}','{1}'...

بۇ قوليازمىنى بىۋاسىتە قاچىلاشقا بولمايدۇ. بۇ باشقا قوليازمىلارنىڭ ئىشلىتىشى ئۈچۈن تەمىنلەنگەن ئامبار بولۇپ، ئىشلىتىش ئۈچۈن مېتا كۆرسەتمىسىگە قىستۇرىدىغان كود: // @require https://update.greatest.deepsurf.us/scripts/453846/1131145/string%20format.js

  1. // ==UserScript==
  2. // @name string format
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.0.2
  5. // @description Format a string with '{0}','{1}'...
  6. // @license Apache License 2.0
  7. // @author 捈荼
  8. // ==/UserScript==
  9.  
  10. // commented by ChatGPT
  11.  
  12. (function () {
  13. "use strict";
  14. // Check if the String.prototype.format function is already defined
  15. if (String.prototype.format == undefined) {
  16. // Define a new function named string_format_V2_0_2
  17. let string_format_V2_0_2 = function () {
  18. // Get the arguments passed to the function
  19. let args = arguments;
  20. // Initialize a counter variable
  21. let cnt = 0;
  22. // Check if the string contains numbered placeholders ({0}, {1}, etc.)
  23. // If not, check if the string contains unnumbered placeholders ({})
  24. return this.match(/{(\d+)}/g) == null && this.match(/{}/g) != null ?
  25. // If the string contains unnumbered placeholders, replace them with the corresponding arguments
  26. this.replace(/{}/g, (match) => {
  27. // If the corresponding argument is defined, return it; otherwise, return the placeholder
  28. return typeof args[cnt] != 'undefined' ? args[cnt++] : match;
  29. }) :
  30. // If the string contains numbered placeholders, replace them with the corresponding arguments
  31. this.replace(/{(\d+)}/g, (match, number) => {
  32. // If the argument at the specified index is defined, return it; otherwise, return the placeholder
  33. return typeof args[number] != 'undefined' ? args[number] : match;
  34. });
  35. };
  36. // Add the new function as the String.prototype.format function
  37. String.prototype.format = string_format_V2_0_2;
  38. } else {
  39. // If the String.prototype.format function is already defined, check if it is the correct implementation
  40. if (String.prototype.format.name != 'string_format_V2_0_2') {
  41. // If the function is not the correct implementation, throw an error
  42. throw 'String.prototype.format defined.';
  43. }
  44. }
  45. })();