...why it is duplicated?
match returns an array where the first entry is the overall match for the entire expression, followed entries for the contents of each capture group you've defined in the regex. Since you've defined a capture group, your array has two entries. The first entry would have leading whitespace if anything matched the \s* at the beginning; the second wouldn't, beause it only has what's in the group.
Here's a simple example:
var rex = /This is a test of (.*)$/;
var str = "This is a test of something really cool";
var match = str.match(rex);
match.forEach(function(entry, index) {
snippet.log(index + ": '" + entry + "'");
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Sometimes there is a comma after the second word other times there is just a space
Your expression won't match that, it's only allowing for a space (and it's only allowing for one of them). If you want to allow a comma as well, and perhaps any number of spaces, then:
/^\s*(\w+[,\s]+\w+)/
Or if you only want to allow one comma, possibly with whitespace on either side
/^\s*(\w+\s*,?\s*+\w+)/
You might also consider two capture groups (one for each word):
/^\s*(\w+)\s*,?\s*+(\w+)/
Example:
var str = "Reed Hastings, CEO Netflix";
var res = str.match(/^\s*(\w+)\s*,?\s*(\w+)/);
if (res) {
snippet.log("Word 1: '" + res[1] + "'");
snippet.log("Word 2: '" + res[2] + "'");
} else {
snippet.log("String didn't match");
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>