替换[b] [/ b]以在DIV上应用BOLD文本

时间:2016-10-24 13:25:48

标签: javascript jquery html ionic-framework

在我的Ionic App上我有一个Textarea,用户可以选择一个文本并使用按钮[BOLD] 在选择周围添加[b] [/ b]。

如何应用BOLD格式化,替换输出文本中的[b] [/ b]?

这就是我的代码。这是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 () {
    $('#TheButton').click(PutTextIntoDiv);
});

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

$( "#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;
    }
});

感谢您的帮助!!

*它与Is it possible to display bold and non-bold text in a textarea?

不重复

因为我不希望格式化textarea中的文本,而是输出OUTPUT文本。

2 个答案:

答案 0 :(得分:2)

考虑PutTextIntoDiv()替换为:

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

JSFiddle中的<pre>应该使<b>正常。

答案 1 :(得分:0)

您可以执行RegEx替换以转换&#34; BBCode&#34;使用.replace(/\[b\](.*)\[\/b\]/g, '<b>$1</b>')将标签转换为html标签。此外,jQuery的.text()会自动对HTML实体进行编码,因此您无法添加样式化文本,因此您应该使用.html()代替。总的来说,您的代码应该是:

function PutTextIntoDiv() {
    var TheText = encodeURIComponent($('#TheTextInput').val());
    $('#TheOutput').html(decodeURIComponent(TheText).replace(/\[b\](.*?)\[\/b\]/g, '<b>$1</b>'));
}

我不确定编码和立即解码uri组件的目的是什么,但我尽量保持不变。这是一个更新的小提琴:http://jsfiddle.net/TheQueue841/62karfm1/

相关问题