pupa
pupa copied to clipboard
Escape dot character
Hi guys,
Sometimes, my data is an object that includes a dot
character.
pupa('The mobile number of {name} is {phone\.mobile}', {
name: 'Sindre',
"phone.mobile": "609 24 363"
});
Maybe should be supported \
character to escape the dot
character.
Sure. That could be supported.
JS simply ignores \
in \.
and returns the string as .
only. So, should the escape character be \\
?
I did some tests considering \\
as the escape character
Changed the regexes in the following lines
https://github.com/sindresorhus/pupa/blob/c9eb13489ebd9dd9e5f0e24c0b64c9f6eb1013dd/index.js#L41 https://github.com/sindresorhus/pupa/blob/c9eb13489ebd9dd9e5f0e24c0b64c9f6eb1013dd/index.js#L47
to
- {{(\d+|[a-z$_][\w$]*?(?:\.[\w$]*?)*?)}}
+ {{(\d+|[a-z$_][\w$]*?(?:\\?\.[\w$]*?)*?)}}
Replaced
https://github.com/sindresorhus/pupa/blob/c9eb13489ebd9dd9e5f0e24c0b64c9f6eb1013dd/index.js#L22-L24
with
for (const property of key.split(/(?<!\\)\./gi)) {
const normalizedProp = property.replace('\\', '');
value = value ? value[normalizedProp] : undefined;
}
The replace('\\', '')
is just to get rid of the extra \
in the template
Then added the following tests,
t.is(pupa('The mobile number of {name} is {phone\\.mobile}', {
name: 'Sindre',
'phone.mobile': '609 24 363',
}), 'The mobile number of Sindre is 609 24 363');
t.is(pupa('The mobile number of {name} is {{phone\\.mobile}}', {
name: 'Sindre',
'phone.mobile': '<b>609 24 363</b>',
}), 'The mobile number of Sindre is <b>609 24 363</b>');
All the tests seem to be passing. If this looks good then I can create a PR
I think the best solution for this is to use a proper parser. https://github.com/sindresorhus/pupa/pull/25 can be used as starting point for anyone wanting to work on this.
Would it be better to use dot-prop
for getting values instead? The escapePath
function would work for this.