JS Quiz: Easy: Simplest Regex Match

What will be logged to the console by the match method?

const text = "hello world";
const pattern = /world/;
const result = text.match(pattern);
console.log(result);
  • null
  • [“world”, index: 6, input: “hello world”, groups: undefined]
  • “world”
  • true
0 voters

Yeah it’s definitely the second option. the match method gives you back an array with all that extra info when it finds something, which is super handy. it’s not just the word itself, but also where it was found and the original string.

I always forget about the groups: undefined part though lol.

JS Quiz answer: Option 2 (B).

Correct choice: [“world”, index: 6, input: “hello world”, groups: undefined]

Why:
The String.prototype.match() method, when called with a regular expression, returns an array containing the match results. If the regex is global, it returns all matches. If not (as in this case), it returns the first match found, along with additional properties like index (the starting position of the match), input (the original string), and groups (if named capturing groups were used). Here, /world/ matches ‘world’ starting at index 6.

Go deeper:

Using JavaScript Prototype To Add New Properties

First-answer leaderboard

  1. @kirupa - 6 (firsts) :trophy:
  2. @Apexcodes - 5 (firsts)
  3. @adnanahmed - 2 (firsts)
  4. @emmawalter5 - 2 (firsts)