-2

I have a text in the following format:

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

I want a regext to get the text after Concept number 1:. So I want to get the following: my content here1.

I was using Concept number 1(.*?)<br>, but I'm getting the whole string as a result instead of the text after the colon.

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>`
Alvaro
  • 40,778
  • 30
  • 164
  • 336

2 Answers2

1

You have to use regex.exec() instead of .match(). Then you can access the matching groups as an ordinary array:

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>
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
1

Personally I would work off the DOM and not the innerHTML

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)
<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>
epascarello
  • 204,599
  • 20
  • 195
  • 236