0

I write a little function to inject pieces of templates to the HTML without the use of "big" templating engines like EJS, Mustache.js, Nunjucks, Pure.js, etc.

I pass this piece of code with a key-value object:

<div><b>@{firstname} @{lastname}</b>, @{gender}</div>

Now I need to remove the extra spaces if someone try to write "@{ firstname }" in place of "@{firstname}".

I'm sorry but I don't know how to write the right ReGex to remove the spaces. How can I remove the spaces?

Thanks for your support.


UPDATE: Thanks to @Saleem for the answer. Here a demo with the fix: https://jsfiddle.net/avq3sntq/

junihh
  • 502
  • 1
  • 9
  • 25

1 Answers1

3

Try following regex:

result = subject.replace(/(@\{)\s*(\S+)\s*(?=})/img, "$1$2");

If you input string is:

<div><b>@{ firstname } @{lastname}</b>, @{gender}</div>

Output will be:

<div><b>@{firstname} @{lastname}</b>, @{gender}</div>

As you can see, removes all extra spaces round firstname inside curly braces. See Demo here

Saleem
  • 8,728
  • 2
  • 20
  • 34