如何选择末尾没有点的段落并删除-使用jQuery/javascript

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

本文关键字:删除 段落 使用 javascript jQuery 何选择 选择      更新时间:2023-09-26

我有以下段落:

<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();

查看Fiddle。

JQuery为此提供了一些非常方便的选择器。尝试:
$('p').each(function(){
    $(this + ':not(:contains(.))').remove();
});

的工作示例