Check if a string contains HTML in JavaScript
Advanced · 4 min read
Comment boxes, chat apps and profile forms all receive text from strangers. Sometimes that text contains HTML, the tags that build web pages, like <p> or <img>. You might want to detect it, to flag a comment for review. More often you want to make sure it can't run on your page. Those are two different jobs, and this tutorial covers both.
First you will write containsHtml, a regular expression that spots tags and entities. Then you will see, with real examples, why a regex must never be used to remove HTML for safety, and what to do instead. You need to know /.../.test(), replace and character classes. Everything else is explained as we go.
What HTML looks like
A tag starts with <, then a name, then optional attributes, then >. A closing tag has a / after the <. An entity is a code for a special character, like < for < or & for &.
<p>hello</p> an opening and a closing tag
<img src="x" alt="y"> a tag with attributes
a < b an entity
Why this matters for safety
If you put someone's text into your page as HTML, any tags in it become part of the page. An image tag with an onerror attribute runs JavaScript when the image fails to load. That attack is called cross-site scripting (XSS), and it lets one user run code in another user's browser.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
19 Does the value contain HTML?
hardDetect whether a string contains HTML. Then face the fact that this is the wrong tool for the job people usually want it for.
Stuck? Three hints, smallest first
- 1. A tag is roughly
<, a name, anything up to>. - 2. HTML is not a regular language, so no pattern can parse it correctly.
- 3. To make text safe, escape it or use
textContent. Never try to strip tags with a regex.
Step 1: detect a tag
Build the tag pattern in pieces:
<\/?is a<and an optional/(for closing tags).[a-z][\w-]*is the tag name: a letter, then letters, digits, underscores or dashes.\wmeans "a letter, digit or underscore".(\s[^<>]*)?is optional attributes: a space, then anything that isn't<or>.\/?>is an optional/and the closing>.
const HTML_TAG = /<\/?[a-z][\w-]*(\s[^<>]*)?\/?>/i;
console.log(HTML_TAG.test('<p>hello</p>')); // true
console.log(HTML_TAG.test('<img src="x" alt="y">')); // true
console.log(HTML_TAG.test('5 < 6 and 7 > 3')); // false
console.log(HTML_TAG.test('I <3 Lagos')); // false
5 < 6 is refused because a space follows the <, not a letter. That keeps math and emoticons from looking like tags.
Step 2: detect entities too
An entity is &, then a name or a number, then ;. #\d+ is a decimal number like ', and #x[0-9a-f]+ is a hex one:
const HTML_TAG = /<\/?[a-z][\w-]*(\s[^<>]*)?\/?>/i;
const HTML_ENTITY = /&(#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);/i;
const containsHtml = (value) =>
typeof value === 'string' && (HTML_TAG.test(value) || HTML_ENTITY.test(value));
console.log(containsHtml('a & b')); // true
console.log(containsHtml('</div>')); // true
console.log(containsHtml('plain text')); // false
That is the detection half. It is fine for flagging. It is not a safety tool, and the next step shows why.
Step 3: the tempting stripper
To "clean" text, many people write a one-line tag remover. <[^>]*> means "a <, anything that isn't >, then >":
const stripTags = (html) => html.replace(/<[^>]*>/g, '');
console.log(stripTags('<p>hello</p>')); // 'hello'
console.log(stripTags('<img src=x onerror=alert(1)>')); // ''
It seems to work. The attack vanished. Now make two small changes.
Step 4: two ways it fails
Leave off the closing bracket:
const stripTags = (html) => html.replace(/<[^>]*>/g, '');
console.log(stripTags('<img src=x onerror=alert(1)')); // '<img src=x onerror=alert(1)'
With no >, the pattern matches nothing, so the whole attack passes through untouched. A browser still reads that unfinished text as an image tag, and the onerror code can run.
Now put a > inside an attribute value:
const stripTags = (html) => html.replace(/<[^>]*>/g, '');
console.log(stripTags('<img src="a>b" onerror="alert(1)">')); // 'b" onerror="alert(1)">'
The match stops at the first >, inside the quotes, and leaves the dangerous onerror behind. These aren't bugs in one pattern. HTML's grammar is too complex for any regular expression to read correctly, so every regex stripper can be beaten like this.
Step 5: escape instead
The safe approach is to escape text: swap the special characters for entities, so the browser shows them as text instead of reading them as HTML. Escape & first, otherwise the & in every new < would be escaped again:
const escapeHtml = (text) =>
String(text)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
console.log(escapeHtml('<img src=x onerror=alert(1)')); // '<img src=x onerror=alert(1)'
console.log(escapeHtml('5 < 6')); // '5 < 6'
The text still reads the same on screen, and none of it can run. In the browser, setting element.textContent does this for you. If you must allow some HTML, use a real sanitizer library such as DOMPurify. Never write your own.
The full solution
The panel has the detector, the escaper and the broken stripper, and prints each failure case. Press Run and read the lines under "stripping does not".
// Detection: does this look like it contains a tag or an entity?
const HTML_TAG = /<\/?[a-z][\w-]*(\s[^<>]*)?\/?>/i;
const HTML_ENTITY = /&(#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);/i;
const containsHtml = (value) =>
typeof value === 'string' && (HTML_TAG.test(value) || HTML_ENTITY.test(value));
// The RIGHT way to make text safe: escape the five characters that matter.
const escapeHtml = (text) =>
String(text)
.replace(/&/g, '&') // & first, or the others get double-escaped
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
// The WRONG way, shown so the failure is concrete rather than a warning.
const stripTags = (html) => html.replace(/<[^>]*>/g, '');
const cases = [
'<p>hello</p>', 'plain text', '<br>', '<img src="x" alt="y">',
'a < b', 'a & b', '5 < 6 and 7 > 3', '<3', 'a<b>c',
];
for (const c of cases) console.log(JSON.stringify(c).padEnd(28), 'contains HTML:', containsHtml(c));
console.log('--- escaping works ---');
console.log('input :', '<script>alert(1)</script>');
console.log('escaped:', escapeHtml('<script>alert(1)</script>'));
console.log('--- stripping does not ---');
console.log('the easy case looks fine:');
console.log(' <img src=x onerror=alert(1)> ->', JSON.stringify(stripTags('<img src=x onerror=alert(1)>')));
console.log('now leave off the closing bracket:');
console.log(' <img src=x onerror=alert(1) ->', JSON.stringify(stripTags('<img src=x onerror=alert(1)')));
console.log(' <- nothing was removed. A browser still parses that as an img tag.');
console.log('and put a > inside an attribute value:');
console.log(' <img src="a>b" onerror="alert(1)"> ->', JSON.stringify(stripTags('<img src="a>b" onerror="alert(1)">')));
console.log(' <- the match stopped at the first >, leaving the onerror behind.');
Output
24 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 24 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a paragraph is detected', containsHtml('<p>hello</p>'), true);
test('a void tag is detected', containsHtml('<br>'), true);
test('a tag with attributes is detected', containsHtml('<img src="x" alt="y">'), true);
test('a closing tag is detected', containsHtml('</div>'), true);
test('plain text is not', containsHtml('plain text'), false);
test('an entity counts as HTML', containsHtml('a < b'), true);
test('and a named entity', containsHtml('a & b'), true);
test('a bare less-than is not a tag', containsHtml('5 < 6 and 7 > 3'), false);
test('nor is an emoticon', containsHtml('<3'), false);
test('escaping neutralises a script tag', escapeHtml('<script>alert(1)</script>'), '<script>alert(1)</script>');
test('the ampersand is escaped first, so nothing is double-escaped', escapeHtml('<'), '&lt;');
test('quotes are escaped, which matters inside an attribute', escapeHtml('a"b\'c'), 'a"b'c');
test('escaped text no longer looks like HTML to the tag pattern', HTML_TAG.test(escapeHtml('<p>x</p>')), false);
test('escaping is reversible in meaning, not destructive', escapeHtml('5 < 6'), '5 < 6');
test('stripping tags removes the obvious case', stripTags('<p>hello</p>'), 'hello');
test('and it looks like it worked on an attack', stripTags('<img src=x onerror=alert(1)>'), '');
test('but an UNTERMINATED tag is not touched at all', stripTags('<img src=x onerror=alert(1)'), '<img src=x onerror=alert(1)');
test('so the whole payload survives, onerror included', stripTags('<img src=x onerror=alert(1)').includes('onerror'), true);
test('and the detector misses it too, since it needs a closing bracket', containsHtml('<img src=x onerror=alert(1)'), false);
test('a > inside an attribute value truncates the match', stripTags('<img src="a>b" onerror="alert(1)">'), 'b" onerror="alert(1)">');
test('leaving the dangerous attribute behind as text', stripTags('<img src="a>b" onerror="alert(1)">').includes('onerror'), true);
test('so stripping is not a security measure', stripTags('<img src=x onerror=alert(1)') === '', false);
test('while escaping handles both cases', escapeHtml('<img src=x onerror=alert(1)'), '<img src=x onerror=alert(1)');
test('and the attribute one', escapeHtml('<img src="a>b">').includes('<'), false);
Detecting HTML is a reasonable thing to want — flagging that a comment field contains markup, say — and the pattern above does it well enough.
The assertions after that are the real content. stripTags looks like it works: <p>hello</p> becomes hello, and even <img src=x onerror=alert(1)> disappears entirely. Two small changes defeat it, and both are asserted.
Leave off the closing bracket — <img src=x onerror=alert(1) — and /<[^>]*>/ matches nothing, so the whole payload passes through untouched. A browser still parses an unterminated tag, so the onerror runs. Note the detector misses it too, for the same reason. Then put a > inside an attribute value: the match stops at that first bracket, and what is left over is b" onerror="alert(1)"> — the dangerous attribute, still there.
These are not gaps in this particular pattern. HTML is not a regular language, so no regular expression can parse it, and every regex tag-stripper has defeats of this kind. It is a fact about the grammar.
So: to display untrusted text, escape it, or set element.textContent and let the browser handle it. To allow some markup, use a real sanitiser with an allow-list — DOMPurify, or the Sanitizer API where available. Never write your own.
Common mistakes
- Stripping tags with a regex to make text safe. An unclosed tag or a
>in an attribute gets through. Escape instead. - Escaping
&last. Then every<you just made turns into&lt;. Do&first. - Trusting the detector as a filter. It misses an unclosed tag too. Use it to flag text, never to decide what is safe.
Try it yourself
- Write
unescapeHtml(text)that turns<back into<and so on. Which entity should you replace last? - Count the tags in
'<p><b>hi</b></p>'withmatchand agversion ofHTML_TAG. - Run
escapeHtmlon'"quoted"'and explain why quotes matter inside an attribute.