pupa icon indicating copy to clipboard operation
pupa copied to clipboard

Escape dot character

Open nghieptiki opened this issue 4 years ago • 5 comments

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.

nghieptiki avatar Dec 14 '20 04:12 nghieptiki

Sure. That could be supported.

sindresorhus avatar Dec 14 '20 06:12 sindresorhus

JS simply ignores \ in \. and returns the string as . only. So, should the escape character be \\?

j-a-h-i-r avatar Jul 14 '21 08:07 j-a-h-i-r

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 &lt;b&gt;609 24 363&lt;/b&gt;');

All the tests seem to be passing. If this looks good then I can create a PR

j-a-h-i-r avatar Jul 14 '21 09:07 j-a-h-i-r

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.

sindresorhus avatar Jan 22 '22 06:01 sindresorhus

Would it be better to use dot-prop for getting values instead? The escapePath function would work for this.

tommy-mitchell avatar Aug 21 '23 01:08 tommy-mitchell