簡體   English   中英

如何用HTML選擇性地替換文本?

[英]How to selectively replace text with HTML?

我有一個應用程序,用戶可以在其中編寫包含HTML代碼的注釋,在顯示之前將其轉義:

<div class="card-body">
 <p class="card-text">
  &lt;h1&gt;HOLA&lt;/h1&gt; Cita:#2&lt;h1&gt;HOLA&lt;/h1&gt; &lt;h1&gt;HOLA&lt;/h1&gt; Cita:#6&lt;h1&gt;HOLA&lt;/h1&gt; &lt;h1&gt;HOLA&lt;/h1&gt; 
 </p>
</div>

但是,當用戶編寫一個特定的單詞,例如“ Cita:#1”時,我想用jQuery將其轉換為鏈接,因此以后我可以使用以下代碼在其中加載Ajax彈出窗口:

$('.card-text').each(function() {
    $(this).html($(this).text().replace(/Cita:#(\d+)/ig, '<a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#$1</a>'));
});

我的問題是,它做得很好,但同時也轉換了該注釋內的所有可能的HTML標簽。

有沒有一種方法可以忽略注釋中的所有標記,而僅用鏈接替換“ Cita:#1”一詞並使之起作用?

實際:

在此處輸入圖片說明

預期:

在此處輸入圖片說明

由於您在此處控制服務器端,因此在PHP中這樣做會容易得多:

$string = '<h1>HOLA</h1> Cita:#2<h1>HOLA</h1> <h1>HOLA</h1> Cita:#6<h1>HOLA</h1> <h1>HOLA</h1>';
$string = htmlspecialchars($string);
$string = preg_replace(
    '/Cita:#(\\d+)/i',
    '<a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#$1</a>',
    $string
);
echo $string;

輸出:

&lt;h1&gt;HOLA&lt;/h1&gt; <a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#2</a>&lt;h1&gt;HOLA&lt;/h1&gt; &lt;h1&gt;HOLA&lt;/h1&gt; <a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#6</a>&lt;h1&gt;HOLA&lt;/h1&gt; &lt;h1&gt;HOLA&lt;/h1&gt;

您需要做的是將文本的匹配部分分開,並將它們作為HTML字符串進行處理,但是對其余文本進行轉義。 由於正則表達式匹配項提供了匹配項的索引,因此這很容易做到。

 $('.card-text').each(function() { var before = ""; var after = $(this).text(); var link = ""; // look for each match in the string while (match = after.match(/\\b(Cita:#(\\d+))\\b/i)) { // isolate the portion before the match and escape it, this will become the output before += $("<div>").text(after.substring(0, match.index)).html(); // isolate the portion after the match, for use in the next loop after = after.substring(match.index + match[1].length); // build a link and append it to our eventual output before += match[1].replace(/Cita:#(\\d+)/i, '<a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#$1</a>'); } // deal with the final bit of the string, which needs to be escaped this.innerHTML = before + $("<div>").text(after).html(); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="card-body"> <p class="card-text"> &lt;span class="foo"&gt;Here is some text. &lt;b&gt;Cita:#1&lt;/b&gt; and &lt;b&gt;Cita:#2&lt;/b&gt;&lt;/span&gt; </p> </div> 


*我們使用jQuery來構建一個元素,將字符串作為該元素的文本內容傳遞,最后得到HTML輸出:

htmlString = "<div>foo</div>";
console.log(
    $("<div>").text(htmlString).html()
);

輸出:

&lt;div&gt;foo&lt;/div&gt;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM