首页 > 解决方案 > 如何用 html 元素替换文本以显示粗体、下划线等?

问题描述

我想在我的网站中实现一些简单的降价操作,例如下面的代码片段。我尝试*<b>**替换</b>,然后意识到这在 Jquery 中并不容易。

在编写此代码段时,我还意识到,只有第一颗星被替换为<b>标签,而我的网站中没有任何东西被此代码替换

$(document).ready(function () {
    $("#convertBtn").on("click", function () {

        $('#questionDisplay').text($("#questionEdit").val());
        $('#questionDisplay').html($('#questionDisplay').text().replace('**', '</b>'));
        $('#questionDisplay').html($('#questionDisplay').text().replace('*', '<b>')); 
     })       
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="questionEdit" rows="5" style="width: 500px;">The user types here many *bold** and *secondBold** texts. The convert button should change the stars to html tags.</textarea>

<button id="convertBtn">Convert</button>
<p>Display: </p>
<p id="questionDisplay"></p>

我用 regEx 解决方案或任何其他方法查看了类似的问题,但我不理解这项工作。所以,事情是:

  1. Jquery中文本到html标签替换的最佳解决方案是什么?
  2. 不是一次,而是所有事件。
  3. 如果可以只用一颗星包裹*boldText*而不是最后两颗星,那就更好了。我尝试使用以下代码执行此操作,但失败了:

$('#questionDisplay').html($('#questionDisplay').html().replace(/_(.*)__/gi, "<b>$1</b>"));

任何帮助将不胜感激!

标签: javascriptjqueryhtmlcssmarkdown

解决方案


分别使用splitjoin打开**<b> </b>replace()将仅替换第一次出现而不是所有出现。

var a;
var b;
$(document).ready(function () {
    $("#convertBtn").on("click", function () {
$('#questionDisplay').text($("#questionEdit").val());
a=$("#questionDisplay").text();
      $('#questionDisplay').html(a.split("**").join('</b>'));
b=a.split("**").join('</b>');
      $('#questionDisplay').html(b.split('*').join('<b>')); 
      
     })       
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="questionEdit" rows="5" style="width: 500px;">The user types here many *bold** and *secondBold** texts. The convert button should change the stars to html tags.</textarea>

<button id="convertBtn">Convert</button>
<p>Display: </p>
<p id="questionDisplay"></p>

对于单星,它变得有点复杂,我们必须使用替换作为拆分和加入不了解优先级。因此,通过替换,我们在运行字符串长度的 while 循环中一一替换星星。将字符串分配给变量的另一种机制保持不变。

  var a;
    var b;
    var i=0;
    $(document).ready(function () {
        $("#convertBtn").on("click", function () {
    $('#questionDisplay').text($("#questionEdit").val());
    a=$("#questionDisplay").text();
    i=a.length;
    while(i--)
    {
          $('#questionDisplay').html(a.replace("*",'<b>'));
    b=a.replace("*",'<b>');
         $('#questionDisplay').html(b.replace("*",'</b>'));
         a=b.replace("*",'</b>');
          
              
         }
         }) 
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <textarea id="questionEdit" rows="5" style="width: 500px;">The user types here many *bold* and *secondBold* texts. The convert button should change the stars to html tags.</textarea>

    <button id="convertBtn">Convert</button>
    <p>Display: </p>
    <p id="questionDisplay"></p>


推荐阅读