From: Dmitry Volyntsev Date: Thu, 12 Nov 2026 02:21:53 +0000 (-0800) Subject: Fix String.prototype.match() returning an empty array on no match X-Git-Url: https://git.kaiwu.me/ngx_http_auth_basic_module.html?a=commitdiff_plain;h=3342479913ffe0bd41a8056b0ba2b5ca52f1c24d;p=njs.git Fix String.prototype.match() returning an empty array on no match Previously, global matching replaced the initial null result with an array even when no matches were collected. This differs from the ECMA-262 RegExp.prototype [ @@match ] algorithm, which returns null when the first execution finds no match. The issue was introduced in 83645861 (0.3.2), which moved array allocation outside the matching loop. Return the array only when it contains matches. Empty-string matches still count as matches, and lastIndex continues to be reset to zero. This closes #1152 issue on GitHub. --- diff --git a/src/njs_string.c b/src/njs_string.c index 272ac4e2..9a601e26 100644 --- a/src/njs_string.c +++ b/src/njs_string.c @@ -2777,7 +2777,9 @@ njs_string_match_multiple(njs_vm_t *vm, njs_value_t *args, } while (p <= end); - njs_set_array(retval, array); + if (array->length != 0) { + njs_set_array(retval, array); + } } return NJS_OK; diff --git a/src/test/njs_unit_test.c b/src/test/njs_unit_test.c index efc64d82..e70beff9 100644 --- a/src/test/njs_unit_test.c +++ b/src/test/njs_unit_test.c @@ -10639,6 +10639,34 @@ static njs_unit_test_t njs_test[] = { njs_str("'ab]cd'.match(/\\]/)"), njs_str("]") }, + { njs_str("'abc'.match(/x/g) === null"), + njs_str("true") }, + + { njs_str("'abc'.match(/(x)/gi) === null"), + njs_str("true") }, + + { njs_str("''.match(/x/g) === null"), + njs_str("true") }, + + { njs_str("'αβγ'.match(/x/g) === null"), + njs_str("true") }, + + { njs_str("'abc'.match(/x/) === null"), + njs_str("true") }, + + { njs_str("var re = /x/g; re.lastIndex = 2;" + "['abc'.match(re) === null, re.lastIndex]"), + njs_str("true,0") }, + + { njs_str("JSON.stringify(''.match(/(?:)/g))"), + njs_str("[\"\"]") }, + + { njs_str("JSON.stringify('abc'.match(/b/g))"), + njs_str("[\"b\"]") }, + + { njs_str("JSON.stringify('αβα'.match(/α/g))"), + njs_str("[\"α\",\"α\"]") }, + { njs_str("'abc'.match(/a*/g)"), njs_str("a,,,") },