Reputation: 7056
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
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('<(/)?b\\s*>', 'gi'), '<$1b>');
Upvotes: 6
Reputation: 2114
This should do it:
$('#output').html($('<div/>').text(text).html().replace(/<(\/?b)>/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