簡體   English   中英

如何選擇末尾沒有點的段落並刪除-使用jQuery / javascript?

[英]How to select paragraphs with no dot at the end and remove - with jQuery/javascript?

我有以下幾段:

<p>This is a first paragraph.</p>
<p>This is a second</p>
<p>A third paragraph is here.</p>
<p>And a fourth</p>

第二段和第四段在句末沒有句號。 有沒有一種方法可以選擇這些段落,然后使用jquery / javascript將其刪除?

$('p').each(function() {
   var par = $(this), text = par.text();
   if (text.charAt(text.length-1) !== '.') {
      par.remove();
   }
});

當然,在點和段落末尾之間不需要多余的空格(或其他字符):在這種情況下,使用正則表達式檢查而不是charAt()可能是更好的選擇

請嘗試以下操作:

$('p').each(function(){
    if(this.innerHTML[this.innerHTML.length - 1] != '.')
        $(this).remove();
});

您的正則表達式是這樣的: <p>.*?(?<!\\.\\s*)</p>

斷言該段不以點結尾,這會給人以負面的印象。

我添加了一個\\s*以在一段時間后留出空間。

我會使用filter而不是each

$("p").filter(function () {
    var text = $(this).text();

    return text.charAt(text.length - 1) != ".";
}).remove();

小提琴

jQuery為此提供了一些非常方便的選擇器。 嘗試:

$('p').each(function(){
    $(this + ':not(:contains(.))').remove();
});

一個有效的例子

暫無
暫無

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

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