Reputation: 25
I am looking for a pattern that will match only if there are two or more names in the string.
I have so far made this:
/(?:\w{2,}\s){2,}/g;
function test() {
var pattern = /(?:\w{2,}\s){2,}/g;
var pse = ps.children;
var poe = po.children
var c = pse.length;
for (i = 0; i < c; i++) {
poe[i].textContent = ""+pse[i].textContent.match(pattern);
}
}
test();
#ps{background-color:#9CFF1C;}
#po{background-color:#AAFFFF;}
<div id="ps">
<p>Name</p>
<p>Name Name</p>
<p>Name Name Name</p>
<p>Name Name Name </p>
</div>
<div id="po">
<p></p>
<p></p>
<p></p>
<p></p>
</div>
<div id="op"></div>
which yields those results. Seems the snippet strips out whitespaces so I can't provide a correct data sample but it would be easy to copy this to another js fidler site.
But I do not want the trailing white space. How do I define the pattern so that the white space is only matched when between words? Or is the problem elsewhere?
Thanks.
Upvotes: 0
Views: 876
Reputation: 13487
I may be misunderstanding you, but what about this?
// The "^" character marks the start of the string
// The "$" character marks the end
// Wrapping your expression with these prevents leading and trailing whitespace
var regex = /^(\w+ )+\w+$/;
// Accepts:
regex.test('Brian Vaughn');
regex.test('Brian David Vaughn');
// Rejects:
regex.test(' Brian Vaughn');
regex.test('Brian Vaughn ');
regex.test('Brian');
Upvotes: 1