Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert tags to html entities

Is it possible to convert html tags to html entities using javascript/jquery using any way possible such as regex or some other way. If yes, then how?

Example:

<div> should be converted to &lt;div&gt;

Note: I am not talking about server-side languages.

like image 630
Sarfraz Avatar asked Apr 10 '10 13:04

Sarfraz


People also ask

How do you convert tags in HTML?

How to convert HTML entities? Copy and paste the text you want to encode or decode. Click on "Start conversion" to add or remove HTML entities. Download your HTML entities text.

What converts special characters to HTML entities?

The htmlentities() function converts characters to HTML entities. Tip: To convert HTML entities back to characters, use the html_entity_decode() function. Tip: Use the get_html_translation_table() function to return the translation table used by htmlentities().

What is HTML entities ()?

htmlentities() Function: The htmlentities() function is an inbuilt function in PHP that is used to transform all characters which are applicable to HTML entities. This function converts all characters that are applicable to HTML entities. Syntax: string htmlentities( $string, $flags, $encoding, $double_encode )


2 Answers

Try this function for the HTML special characters:

function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}
like image 144
Gumbo Avatar answered Oct 04 '22 07:10

Gumbo


As you tagged with jquery, a jQuery-powered solution should work for you:

$("<div>").text("<div>bleh</div>whatever").html()

Replace the argument to the text-method with whatever markup you want to escape.

like image 35
Jörn Zaefferer Avatar answered Oct 04 '22 05:10

Jörn Zaefferer