|
12 | 12 | * count: 2, |
13 | 13 | * }); |
14 | 14 | * // => 'Hello John, you have 2 messages.' |
15 | | - * * interpolate('Hello {{name}}, you have {{count}} {{count|message|messages}}.', { |
| 15 | + * |
| 16 | + * interpolate('Hello {{name}}, you have {{count}} {{count|message|messages}}.', { |
16 | 17 | * name: 'John', |
17 | 18 | * count: 1, |
18 | 19 | * }); |
|
23 | 24 | * @param variables - An object of variables |
24 | 25 | * @returns The interpolated string |
25 | 26 | */ |
26 | | -// the following regex is bounded, avoids nested repetition, and is safe for controlled templates |
| 27 | + |
27 | 28 | // eslint-disable-next-line security/detect-unsafe-regex, sonarjs/slow-regex |
28 | | -const interpolationPattern = /{{\s*(\w+)(?:\|([^|]+)\|([^|]+))?\s*}}/g; |
| 29 | +const interpolationPattern = /{{\s*([^}|]+)(?:\|([^}|]+)\|([^}]+))?\s*}}/g; |
29 | 30 |
|
30 | 31 | export function interpolate( |
31 | 32 | template: string, |
32 | 33 | variables: Record<string, string | number> = {} |
33 | 34 | ): string { |
34 | 35 | // eslint-disable-next-line unicorn/prefer-string-replace-all |
35 | | - return template.replace(interpolationPattern, (_, token) => { |
36 | | - const parts = token.split('|').map((part: string) => part.trim()); |
| 36 | + return template.replace(interpolationPattern, (_match, variable, singular, plural) => { |
| 37 | + const key = variable.trim(); |
| 38 | + const value = variables[key]; |
| 39 | + |
| 40 | + if (singular !== undefined && plural !== undefined) { |
| 41 | + const count = Number(value); |
37 | 42 |
|
38 | | - if (parts.length === 3) { |
39 | | - const [variable, singular, plural] = parts; |
40 | | - const value = Number(variables[variable]); |
41 | | - if (Number.isNaN(value)) return plural; |
42 | | - return value === 1 ? singular : plural; |
| 43 | + if (Number.isNaN(count)) return plural; |
| 44 | + return count === 1 ? singular : plural; |
43 | 45 | } |
44 | 46 |
|
45 | | - const value = variables[parts[0]]; |
46 | 47 | return value == null ? '' : String(value); |
47 | 48 | }); |
48 | 49 | } |
0 commit comments