Reputation: 2201
I have a string of HTML with handlebars like the following:
var text = '<p>This is the {{description}}</p><pre><code class="hljs">{{capitalize property}}</code></pre>'
I would like to search through the string and replace the handlebars brackets (i.e. {
and }
) with another character (in this case, a string that represents the html entity. For example, {
and }
, respectively) only when the handlebars are between opening and closing code tags (note, the tags can have a class).
Thus, the above string would look like this:
var text = '<p>This is the {{description}}</p><pre><code class="hljs">{{capitalize property}}</code></pre>'
Possible Options:
I understand I could append the string to the document and manipulate it with jQuery. I am also aware of the DOMparser()
method.
Is there a simple way to achieve what I am trying, in Javascript? And would that method have major performance disadvantages?
My attempts have looked something like this:
string.replace(/<code[^>]*>({)<\/code>/g, '{');
Upvotes: 0
Views: 132
Reputation: 1864
Using regular expressions to parse HTML code can be really slow or result unexpected consequences.
Anyhow, this code tries to locate all <code>
blocks and replaces {{
and }}
with [[
and ]]
. Code block can have multiple attributes.
text.replace(/<code(?:\s+[^>]+)*>(?:.*?{{.+?}})*.*<\/code>/g, function(a) {
return(a.replace(/{{/g, "[[").replace(/}}/g, "]]"));
})
Upvotes: 1