Skip to content

i18n: replace placeholder using replacer callback #14109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 10, 2022
Merged

Conversation

connorjclark
Copy link
Collaborator

@connorjclark connorjclark commented Jun 9, 2022

from chat:

replacing strings literally in JS is actually pretty not straightforward. Worse, it will work in like 99% of cases until it doesn't. See:

const replaceWith = 'Dollar: \'$\');';
console.log('REPLACE'.replace('REPLACE', replaceWith));

this prints Dollar: '); ... note the missing dollar sign ... because the replace function is "regex-aware" even if the first parameter is not a regex ...

only valid for $' and $`. the others ($0, $1) don't work

so you must do this:

'REPLACE'.replace('REPLACE', () => replaceWith);

After auditing all our usages of String.prototype.replace, I only found this one instance where it could theoretically be problematic.

@connorjclark connorjclark requested a review from a team as a code owner June 9, 2022 22:54
@connorjclark connorjclark requested review from adamraine and removed request for a team June 9, 2022 22:54
@adamraine
Copy link
Member

because the replace function is "regex-aware" even if the first parameter is not a regex ...

What exactly does "regex-aware" mean? It considers $ to be EOL rather than a dollar sign character?

@connorjclark
Copy link
Collaborator Author

connorjclark commented Jun 9, 2022

It considers $ to be EOL rather than a dollar sign character?

nope

It means that various patterns you might only associate with regex are still applied. See:

image

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter

@paulirish paulirish merged commit 0cd8664 into master Jun 10, 2022
@paulirish paulirish deleted the i18n-replace-cb branch June 10, 2022 00:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants