在冒号之后和新行之前匹配文本 - Javascript

时间:2017-11-01 15:53:56

标签: javascript regex

我的文字格式如下:

Concept number 1: my content here1<br>
Concept number 2: my content here2<br>
Concept number 3: my content here3<br>

我想要一个regext来获取Concept number 1:之后的文本。所以我希望得到以下内容:my content here1

我使用的是Concept number 1(.*?)<br>,但我得到了整个字符串而不是冒号后的文字。

Demo online

var text = $('.text').html();
var regex = new RegExp('Concept number 1:(.*?)<br>', "g");
var matches = text.match(regex);
//matches contains `Concept number 1: my content here1<br>`

2 个答案:

答案 0 :(得分:1)

您必须使用regex.exec()代替.match()。然后,您可以将匹配的组作为普通数组访问:

var text = $('.text').html();
var regex = new RegExp('Concept number 1:(.*?)<br>');
var matches = regex.exec(text);

console.log(matches[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
Concept number 1: my content here1<br>
Concept number 2: my content here2<br>
Concept number 3: my content here3<br>
</div>

答案 1 :(得分:1)

就个人而言,我会解决DOM而不是innerHTML

&#13;
&#13;
var text = $('.text').contents()  //get all the textnodes and elements
             .filter( function (i, node) { //get just the text nodes
               return node.nodeType==3
             }).map( function (i, node) {  //get the text you are after
               var match = node.nodeValue.match(/:\s+(.*)/)
               return match ? match[1] : undefined
            }).get()  //turn jQuery object into array
console.log(text)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
Concept number 1: my content here1<br>
Concept number 2: my content here2<br>
Concept number 3: my content here3<br>
</div>
&#13;
&#13;
&#13;