Search code examples
javascriptregexecmascript-6regex-group

Regex Grouping Stepped Explanation


let quotedText = /'([^']*)'/;
console.log(quotedText.exec("she said 'hello'"));
//["'hello'", "hello"]

why does hello appear twice?


Solution

  • The first element in the result is the full match, and the second element is the first captured group. Remove the parentheses () to get only one result.

    let quotedText = /'[^']*'/;
    console.log(quotedText.exec("she said 'hello'"));

    If you still want to keep the parentheses, you can use a non-capturing group as shown below:

    let quotedText = /'(?:[^']*)'/;
    console.log(quotedText.exec("she said 'hello'"));