0

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, &#123; and &#125;, 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">&#123;&#123;capitalize property&#125;&#125;</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, '&#123;');
1
  • 2
    You need to use an HTML parser. Commented May 25, 2014 at 2:49

1 Answer 1

1

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, "]]"));
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.