匹配字符串中的第二个句子

时间:2019-08-10 22:56:27

标签: javascript html regex

我有一个文本如下的元素:

<div class="element">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

我想将本文中的第二个句子作为目标,通常以. ? !或换行符结束。

function add_br(){

    //Assigning the element to a variable
    var element = document.getElementsByClassName('element')[0];

    //Find the 2nd sentence.
    ..

    //Add <br> after it
    ..
}

那么如何定位第二句并在其后添加<br>

这里是一个示例,我们假设这是文本:

<div class="element">
    This is the first sentence. This is the second sentence! Is this the 3rd sentence? ..
</div>

最终结果应该是:

<div class="element">
    This is the first sentence. This is the second sentence! <br> Is this the 3rd sentence? ..
</div>

1 个答案:

答案 0 :(得分:1)

在正则表达式中使用split

split()方法将分度符作为参数,我们可以使用正则表达式使多个分度符成为

这是JS Regex中特殊字符的完整列表,需要用反斜杠转义:[ \ ^ $ . | ? * + ( )

所以我们可以使用\.!\? ..

一起:/[\.!\?]+/

function append_br(){
    var result='';

    document.getElementsByClassName('element')[0]
      .innerHTML.split(/[\.!\?]/)
      .forEach(sentence => result += sentence.concat("<br>"));

    return result;
}

基于以下链接:

编辑:经过测试,修复并可以正常工作。