0

Suppose a template javascript string like this:

js_string = u'function hello() { alert({0}); } function goodbye() { alert({1}); }'

I would like to get following result:

function hello() { alert('Hello!'); } function goodbye() { alert('Goodbye!'); }

My initial idea was to use the .format() method, which resulted in a KeyError due to the arbitrary curly braces. I then had a look at this question and replaced said curly braces with double curly braces. Although this produces the desired result, I cannot use it, as I'm working with a rather large javascript template and am not up for changing each and every single curly brace.

I have also tried the .replace() function:

js_string.replace("{0}", repr("Hello!")).replace("{1}", repr("Goodbye!"))

However, calling .replace() more than once seems inconvenient to me, which is why I am asking if there is any straightforward alternative for this problem.

sfritsch
  • 3
  • 2
  • Are you inserting anything other than data into the template? You could just make a template with only variable definitions and add the actual code separately. – Alex Hall Jul 04 '17 at 20:44

3 Answers3

0

You could do the replacement with one call to sub by supplying a callback function that reads the number inside braces, and grabs the corresponding replacement word from a list:

re.sub(r'\{(\d+)\}', lambda m: ["'hello'", "'Goodbye!'"][int(m.group(1))], js_string)
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Use string interpolation with the % operator:

>>> u'function hello() { alert(%r); } function goodbye() { alert(%r); }' % ('Hello', 'Goodbye')
"function hello() { alert('Hello'); } function goodbye() { alert('Goodbye'); }"

Here %r means use the repr, if you want to insert the string directly use %s. %% is a literal %.

More details: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

If you're set on curly brace syntax, you can simply call .replace in a loop. No need for regexes.

for i, replacement in enumerate(["'hello'", "'Goodbye!'"]):
    js_string = js_string.replace('{%s}' % i, replacement)
Alex Hall
  • 34,833
  • 5
  • 57
  • 89