zgid123 / string-interpolation-js

Lightweight package to format string template to a new string that is replaced all parameters with provided data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to escape interpolation patterns?

NLKNguyen opened this issue · comments

Hi, is there any support for escaping interpolation patterns when they need to be treated as raw literals?

For example, if my pattern is ${ _ }, and when I need "${ name }" to not be interpolated, I need a way to escape the pattern indicator, such as "$${ name }"

Is there already a way to do something like this? If not, I'm thinking that a config option for a simple prefix character as the escape indicator would be sufficient.

Thanks for the work!

Hi. I am not sure that I understand your idea. Please give me some samples.

So basically, you want something like this

const a = '${ name } $${ name }';

const b = interpole(a, { name: 'test' }); // result is 'test $${ name }'

If that case, this package still not support it. It will take time to support this one, a PR is welcome 😄

It's more like this:

const a = '${ name } $${ name }';

const b = interpole(a, { name: 'test' }); // result is 'test ${ name }'

I picked $$ purely as an example of Docker-Compose way of presenting a literal $ so that the sequence is not treated as a variable reference for substitution by the docker environment value. It's commonly used when you want the shell commands in Docker Compose that use similar variable syntax to be treated raw so that only when the container runs, then the variables will be evaluated by the shell runtime.

In JS interpolation, the escape char is \ instead

image

Whereas in PowerShell the escape is backtick `

image

This type of escaping interpolation is quite common, and the escape indicator is arbitrary. That's why I'm interested in an option to specify that. I understand that it's not supported yet. This is the missing piece for my use case with this cool library :)

I'm working on this project that I have a need for customizable interpolation syntax https://github.com/NLKNguyen/code-formation

What if we have this one

const a = '${ name } $${ name } ${ a } $${ a }';

const b = interpole(a, { name: 'test' }); // what is the result?

${ a } alone should throw an error because a is not in the supplied variables that you pass in the interpolate method { name: 'test' }.

Here in JS syntax, I use \ as an escape character for $ instead
image

The error is a commonly expected behavior, but let's assume you default any unknown variable to an empty string (many shells do that), then the result should be: test ${ name } ${ a }

image

@NLKNguyen version 1.0.5 will support your case