javascript - 替换 [b][/b] 以在 DIV 上应用粗体文本

标签 javascript jquery html ionic-framework

在我的 Ionic 应用程序上,我有一个文本区域,用户可以在其中选择文本并使用按钮 [BOLD] 在所选内容周围添加 [b] [/b]。

如何应用粗体格式,替换输出文本上的 [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? 不重复

因为我不想格式化文本区域内的文本,而是格式化输出文本。

最佳答案

考虑PutTextIntoDiv()替换为:

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

<pre>在你的 JSFiddle 中应该呈现 <b>美好的。

关于javascript - 替换 [b][/b] 以在 DIV 上应用粗体文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40219674/

相关文章:

javascript - 在ajax jquery中显示json响应,

javascript - 数组函数不是函数

javascript - 调整由鼠标滚轮触发的 Cytoscape.js 中的缩放比例

jquery - 如果它们已经属于一个类,我如何在 jquery 中命名和选择一组元素?

java - 我如何更改此设置以用 html 页面替换 404 页面错误?

css - 如果我的浏览器窗口小于 div 的内容,当我向右滚动时,100% 宽度的 div 会被截断

javascript - 使用 "forEach"有什么问题?

jquery - webservice - 未知的 Web 方法参数名称 methodname

javascript - 每 2 秒多次运行相同的 javascript 函数

javascript - 如何绕过 jQuery 验证