Skip to content

Replace every placeholder in string.format and insert args literally - #10107

Open
SwastikTripathi wants to merge 1 commit into
playcanvas:mainfrom
SwastikTripathi:fix/string-format-all-placeholders
Open

SwastikTripathi wants to merge 1 commit into
playcanvas:mainfrom
SwastikTripathi:fix/string-format-all-placeholders

Conversation

@SwastikTripathi

Copy link
Copy Markdown
Contributor

string.format() calls String#replace with a string pattern once per argument, which gives three surprises for a public helper:

string.format('{0} and {0}', 'abc');      // "abc and {0}", expected "abc and abc"
string.format('cost: {0}', '$&5');         // "cost: {0}5", expected "cost: $&5"
string.format('{0} {1}', '{1}', 'x');      // "x {1}", expected "{1} x"

A string pattern only replaces the first match, the replacement string is scanned for $&, $1, $$ and similar patterns, and since each argument is substituted into the result of the previous pass, a {1} inside the first argument gets replaced by the second one.

format() now does a single replace with a /\{(0|[1-9]\d*)\}/g regex and a replacer function. Every occurrence is replaced, the argument text goes in as-is (a replacer's return value is not scanned for $ patterns), and nothing inside an argument is substituted again. Placeholders without a matching argument stay untouched, as before. Inputs that worked before give the same output, including the undefined text for an explicit undefined argument.

Tests: four new cases in test/core/string.test.mjs (repeated placeholder, $ patterns in args, {n} inside an arg, placeholder without an arg). The first three fail before the change, all 12 pass after. eslint is clean on both files.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant