Mihkel L.
Mihkel L.

Reputation: 1573

Javascript JS optional

So the following regular expression re works in JAVA but not in javascript. It looks like a very basic question. How can I make it so, that the [A-Za-z]+ part would be optional in js?

var re = /\w+\s+[A-Za-z]+?/g;
var str = "John Smith";
$("#ret1").text(re.test(str)); // true
$("#ret12").text(re.test("sssa "));// false

Upvotes: 2

Views: 65

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

To match 0 or more characters (as your intent seems to be), you need to use * quantifier:

\w+\s+[A-Za-z]*
              ^

See demo

The +? quantifier requires to match at least 1 character and more, but as few as possible to return a valid match.

I see you confused ? and *? quantifiers. When adding ? after + or * the former turn into the so-called lazy quantifiers meaning they will match 0 (*) or 1 (+) characters and then any more characters but as few as possible. Here is an excerpt from rexegg.com with the quantifiers supported by JavaScript engine:

A+ - One or more As, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)

A+? One or more As, as few as needed to allow the overall pattern to match (lazy)

A* Zero or more As, as many as possible (greedy), giving up characters if the engine needs to backtrack (docile)

A*? Zero or more As, as few as needed to allow the overall pattern to match (lazy)

A? Zero or one A, one if possible (greedy), giving up the character if the engine needs to backtrack (docile)

A?? Zero or one A, zero if that still allows the overall pattern to match (lazy)

Upvotes: 5

Related Questions