从特定类中删除最后一个单词

时间:2018-03-15 16:49:32

标签: javascript jquery class

我想从某些类中的每个句子中删除最后一个特定单词。例如:

<p class="remove">Active speakers hire</p>
<p class="remove">Passive speakers hire</p>

我想删除&#34;雇用&#34;来自每个包含&#34;删除&#34;附属于它的课程。我知道这可以使用以下代码单独完成:

var str = "Active speakers hire";
var lastIndex = str.lastIndexOf(" ");

str = str.substring(0, lastIndex); 

但是如何在基于类的外部jquery文件中做到这一点?我不想为每个段落分别输入js代码。感谢

4 个答案:

答案 0 :(得分:7)

您可以使用text-function尝试此操作,例如:

&#13;
&#13;
$('.remove').text(function(i, txt) {
  return txt.substring(0, txt.lastIndexOf(" "));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="remove">Active speakers hire</p>
<p class="remove">Passive speakers hire</p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用jQuery&#39; .each函数。

$(".remove").each(function() {
    var str = this.html()
    var lastIndex = str.lastIndexOf(" ");
    this.html(str.substring(0, lastIndex));
});

答案 2 :(得分:0)

不需要jQuery:

&#13;
&#13;
var items = document.getElementsByClassName('remove');

[].forEach.call(items, item => {
 var newText = item.innerHTML.split(' ');
 newText.pop();
 item.innerHTML = newText.join(' ');
});
&#13;
<p class="remove">Active speakers hire</p>
<p class="remove">Passive speakers hire</p>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

由于NodeList.forEach(),以下解决方案在IE中无法正常工作,但它没有依赖关系。

stu1

要使其在IE中运行,您必须以其他方式迭代节点列表,但我认为这不是问题。

Fiddle

相关问题