Tim
Tim

Reputation: 7056

jquery turn text tags to html tags

I have a field that fills in a div similar to how the asking a question works here on stackoverflow.

    var text = $("#edit").val();
    $("#output").text(text);

I want to be able to use a selected few html tags, like <b> bold for example. When I try this at the moment, the tags come up as text rather than html. If possible I want to be able to search for specific tags and make them into html.

Can anyone help?

thanks

Upvotes: 3

Views: 6726

Answers (3)

Jaroslav Jandek
Jaroslav Jandek

Reputation: 9563

Use the .html() function instead of the .text() function, escape everything except the <b> tags.

Edit: The method could would vary based on how many tags you want to keep and how many to encode.
This will keep the <b> tag:

var text = 'This is <i>encoded text</i> but this is <b>bold</b >!';
var html = $('<div/>')
    .text(text)
    .html()
    .replace(new RegExp('&lt;(/)?b\\s*&gt;', 'gi'), '<$1b>');

Upvotes: 6

Andrew
Andrew

Reputation: 2114

This should do it:

$('#output').html($('<div/>').text(text).html().replace(/&lt;(\/?b)&gt;/g, '<$1>'));

Obviously if you wanted to allow more than just tags, your regex might get quite complicated, but essentially you've either got to selectively encode, or encode everything and then selectively decode. The latter seems safer.

Upvotes: 1

Mark Hildreth
Mark Hildreth

Reputation: 43071

Try using...

$("#output").html(text);

Docs

Upvotes: 1

Related Questions