Interpret the html string with descriptors, but avoid script tags

I am providing an html string for my page, and I consider it html-safe, with the exception of script tags. I know that triple curly braces will exit html, what are the steps to exclude script tags?

Example

var foo = "<h1>Foo</h1><script>some script that might possibly be in here</script><p>bar</p> 

then in my .hbs:

 {{{foo}}} 

I would like to see h1 and the paragraph, but you still have scripts.

Thanks in advance.

+6
source share
1 answer

You have several options:

  • Remove the script tags before passing it as a context to your Handlebars template.

  • Create a Handlebars helper to use expressions instead of a brace. Something like that:

  Handlebars.registerHelper('strip-scripts', function(context) { var html = context; // context variable is the HTML you will pass into the helper // Strip the script tags from the html, and return it as a Handlebars.SafeString return new Handlebars.SafeString(html); }); 

Then use it in your template as follows:

  {{strip-scripts foo}} 

You do not need to use triple braces when using the helper, because your helper already returns a SafeString.

A helper may be more useful than the first option, because you can reuse it in all of your templates.

Check out this question in StackOverflow for help on how to safely erase script tags: Removing all script tags from html using JS regex

If you are doing this server side using Node.js, you can use something like Cheerio instead of jQuery.

+5
source

All Articles