Rafael de Castro Rafael de Castro - 2 months ago 25
jQuery Question

Replacing [b][/b] to apply BOLD text on a DIV

On my Ionic App I have a Textarea where the user can select a text and with button [BOLD]
add [b] [/b] around the selection.

How can I apply BOLD formating, replacing the [b] [/b] on the output text?

Thats my code. And here's the JsFiddle

<textarea id="TheTextInput" rows="5"></textarea>
<input type="button" id="TheButton" value="click" />
<input type="button" id="bold" value="BOLD" />
<pre id="TheOutput"></pre>

$(document).ready(function () {

function PutTextIntoDiv() {
var TheText = encodeURIComponent($('#TheTextInput').val());

$( "#bold" ).click(function() {
var textArea = document.getElementById("TheTextInput");
if (typeof(textArea.selectionStart) != "undefined") {
var begin = textArea.value.substr(0, textArea.selectionStart);
var selection = textArea.value.substr(textArea.selectionStart, textArea.selectionEnd - textArea.selectionStart);
var end = textArea.value.substr(textArea.selectionEnd);
textArea.value = begin + '[b]' + selection + '[/b]' + end;

Thanks for your help!!

*Its not duplicate from How do display bold and non-bold text in textarea?

Cause I don't want format the text inside the textarea, but the OUTPUT text.


Consider PutTextIntoDiv() replacing with:

function PutTextIntoDiv() {
    $('#TheOutput').html($('#TheTextInput').val().replace(/\[b\]/g, '<b>').replace(/\[\/b\]/g, '</b>'));

The <pre> in your JSFiddle should render <b> fine.