-2

When parsing this

<title>I have a cat</title> <div class="chat_message_wrapper chat_message_right">

with

var re_title = new RegExp("<title>(.*?)</title>");
var content = xmlhttp.responseText;
// var title = re_title.exec(content);
var title = content.match(re_title);

// title = strip(title);
alert(title);

for some reason, I get this in an alert:

<title>I have a cat</title>,I have a cat

How can I only get the “I have a cat” part?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Christina
  • 39
  • 5

1 Answers1

1

The match method returns an array with first the complete match, and in the other elements the capture groups. Since you have one capture group, you need to get the value from the array at index 1:

 title[1]
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Note: if there's a possibility the regex won't match at all you should also test if `title` is `null` before trying to access `title[1]`. – nnnnnn Feb 24 '17 at 23:09
  • Then I might as well add that HTML should not be parsed with regular expressions... – trincot Feb 24 '17 at 23:15