Peter Kellner
Peter Kellner

Reputation: 15508

how to display a script tag in html and not execute it

I want to display a script tag that looks like: <script..

if I run JavaScript

encodeURI("<script")

Then output that to the browser it no longer looks like < script

I'm strong it on my backend with the real less than sign but want to convert it with javascript, then display that conversion as html I assume with <

Is there a javascript function that will do this? (obviously not encodeURI)

thanks

Upvotes: 1

Views: 3814

Answers (2)

Alireza Fattahi
Alireza Fattahi

Reputation: 45603

You must use a method or a tool which escapes some html characters.

For a tool please see http://www.iwantaneff.in/entifier/ for sample

So your code will be

&lt;script&gt;

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59282

There is no native function, but you can manually create one:

function htmlEscape(str) {
    return str.replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

You can manually do replace like that.

Call it like this:

htmlEscape('<script');

Upvotes: 1

Related Questions