Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8418903
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T02:27:26+00:00 2026-06-10T02:27:26+00:00

I want to safely display a text coming from the user (by blocking scripts

  • 0

I want to safely display a text coming from the user (by blocking scripts tags), but I need to accept html markups (b, p, li, ul, etc.).

It’s need to be bullet proof against cross-site scripting attack.

Thank you!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T02:27:28+00:00Added an answer on June 10, 2026 at 2:27 am

    If you have a simple tag whitelist and you don’t need to worry about attacks at or below the encoding level (as is the case from within browser-side JavaScript), you can do the following:

    function sanitize(tagWhitelist, html) {
      // Get rid of all uses of '['.
      html = String(html).replace(/\[/g, '[');
    
      // Consider all uses of '<' and replace whitelisted tags with markers like
      // [1] which are indices into a list of approved tag names.
      // Replace all other uses of < and > with entities.
      var tags = [];
      html = html.replace(
        /<!--[\s\S]*?-->|<(\/?)([a-z]\w*)(?:[^"'>]|"[^"]*"|'[^']*')*>/g,
        function (_, close, tagName) {
          if (tagName) {
            tagName = tagName.toLowerCase();
            if (tagWhitelist.hasOwnProperty(tagName) && tagWhitelist[tagName]) {
              var index = tags.length;
              tags.push('<' + (close || '') + tagName + '>');
              return '[' + index + ']';
            }
          }
          return '';
        });
    
      // Escape HTML special characters.  Leave entities alone.
      html = html.replace(/[<>"'@\`\u0000]/g,
        function (c) {
          switch (c) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '"': return '&quot;';
            case '\'': return '&#39;';
            case '@': return '&#64;';
          }
          return '&#' + c.charCodeAt(0) + ';';
        });
      if (html.indexOf('<') >= 0) { throw new Error(); }  // Sanity check.
    
      // Throw out any close tags that don't correspond to start tags.
      // If <table> is used for formatting, embedded HTML shouldn't be able
      // to use a mismatched </table> to break page layout.
      var open = [];
      for (var i = 0, n = tags.length; i < n; ++i) {
        var tag = tags[i];
        if (tag.charAt(1) === '/') {
          var idx = open.lastIndexOf(tag);
          if (idx < 0) { tags[i] = ""; }  // Drop close tag.
          else {
            tags[i] = open.slice(idx).reverse().join('');
            open.length = idx;
          }
        } else if (!HTML5_VOID_ELEMENTS.test(tag)) {
          open.push('</' + tag.substring(1));
        }
      }
      // Now html contains no tags or less-than characters that could become
      // part of a tag via a replacement operation and tags only contains
      // approved tags.
      // Reinsert the white-listed tags.
      html = html.replace(
           /\[(\d+)\]/g, function (_, index) { return tags[index]; });
    
      // Close any still open tags.
      // This prevents unclosed formatting elements like <ol> and <table> from
      // breaking the layout of containing HTML.
      return html + open.reverse().join('');
    }
    
    var HTML5_VOID_ELEMENTS = new RegExp(
         '^<(?:area|base|br|col|command|embed|hr|img|input'
         + '|keygen|link|meta|param|source|track|wbr)\\b');
    

    which can be used like

    sanitize({ p: true, b: true, i: true, br: true },
             "Hello, <b>World</b>!<script>alert(1337)<\/script>");
    

    If you need more configurability, like the ability to allow attributes on tags, see the Caja HTML sanitizer.

    As others have pointed out, your server should not trust the result coming from the client so you should re-sanitize on the server before embedding the result into server-generated markup.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want user to be able to paste their html/css code? eg. from internet.
Specifically common.inc. I need to modify format_date, but I want to do it safely.
I want to remove all php tags from a external text so it can
I want to create django users from django application, and then confirming user creation
i need to convert pointers to long (SendMessage()) and i want to safely check
I want to generate filename from a user-inputed string and to make sure that
I want to remove the clearfix class from my HTML and include a clearfix
I have rendered one of my controls into a string. I want to safely
Long-time joelonsoftware follower, 1st-time stackoverflow poster. I want to know how safely I can
want to open pdf file when a user clicks on hyperlink shown in gridview

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.