Roy
Roy

Reputation: 783

Interpreting this piece of JavaScript

I'd like to understand what this line of JavaScript means...

(/^\w+, ?\w+, ?\w\.?$/)

i understand 'w stands for 'word', but need your help in understanding '/', '^', '+', '?', '.?$/'

Thank you..

Upvotes: 2

Views: 132

Answers (5)

adam0101
adam0101

Reputation: 31005

It's a regular expression that looks for a string of word characters (like letters, digits, or underscores) that has two commas in it with an optional single space after each comma.

Upvotes: 1

Paul Beckingham
Paul Beckingham

Reputation: 14905

Let's break it down, because then it is easier to read:

^        beginning of the line
\w+      1 or more 'word' characters
,        a comma
 ?       an optional space
\w+      1 or more 'word' characters
,        a comma
 ?       an optional space
\w       a single 'word' character
\.?      an optional period
$        end of line

The meaning of a 'word' character is an alpha-numeric character or an underscore.

Upvotes: 2

pestaa
pestaa

Reputation: 4749

/^\w+, ?\w+, ?\w\.?$/

Outside in...

  • / / delimiters
  • ^ $ Matches the whole string (^ means to match the beginning, $ means to match the end)

One by one...

  • \w means word character (simply w doesn't match anything but the ASCII character w)
  • \w+ word characters (at least one, matches as much as possible)
  • ? means the spaces are optional, matches 0 or 1 space character
  • . matches any character that is not a line break (can be configured with regex modifiers)
  • \. (like in the example) matches exactly one dot

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382746

It is not HTML code but Regular Expression. Read more about it:


In computing, regular expressions, also referred to as regex or regexp, provide a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. A regular expression is written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.

Upvotes: 1

SLaks
SLaks

Reputation: 887469

That's a regular expression, not HTML.

It's inside of a regex literal (/.../) in Javascript.

  • ^ matches the beginning of the string
  • \w matches any word character
  • + matches one or more of the previous set.
  • ? matches zero or one of the previous set (in this case a single space)
  • \. matches a .. (An unescaped . matches any single character)
  • $ matches the end of the string.

Upvotes: 2

Related Questions