I’m trying to do a simple RegEx match as below:
var page = "<title>Hello, World!</title>";
var pattern = /<title>(.*?)<\/title>/i;
var title = pattern.exec(page);
document.write(title);
For some reason, the results look like:
,Hello, World!
Any idea why the comma is being added to the start?
pattern.exec()returns an array. The first item in the returned array is the entire match. The second item in the returned array is the first matched group. You’re callingdocument.write()on an array of two elements, not on a single string. Array entries are separated by commas when output in many circumstances. You don’t see the first item in the array because it’s this HTML<title>Hello, World!</title>which is invisible. Then, there’s a comma between that element and the next element which is the text you want.Your code should probably be this:
You can see it work here: http://jsfiddle.net/jfriend00/BQ33Q/