Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Grouping Stepped Explanation

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

why does hello appear twice?

like image 762
amissak Avatar asked Jan 21 '26 07:01

amissak


1 Answers

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'"));
like image 141
Unmitigated Avatar answered Jan 22 '26 19:01

Unmitigated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!