From 3ffc1e232b07f3fa3e5fb868d15a11d74bcebc58 Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Mon, 30 Mar 2020 11:21:05 +0200 Subject: [PATCH] no infinite loop on non global regex --- index.js | 6 ++++++ test/index.js | 29 +++++++++++++++++++++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index c2feb41..3e812b7 100644 --- a/index.js +++ b/index.js @@ -53,6 +53,12 @@ function copy_object (obj) { * @param {any} func function to execute */ function run_regex (regex, data, func) { + if (!regex.global) { + const result = regex.exec (data); + if (result) + func (result); + return; + } let res = regex.exec (data); while (res) { func (res); diff --git a/test/index.js b/test/index.js index 30d2d4b..05787e0 100644 --- a/test/index.js +++ b/test/index.js @@ -45,9 +45,30 @@ test ('run regex', (t) => { const data = 'foobarfoo'; const regex = /foo/gu; let count = 0; - util.run_regex(regex,data,(res)=>{ - t.is(res[0], 'foo'); + util.run_regex (regex, data, (res) => { + t.is (res[0], 'foo'); count++; - }) - t.is(count, 2); + }); + t.is (count, 2); +}); + +test ('run non-global regex', (t) => { + const data = 'foobarfoo'; + const regex = /foo/u; + let count = 0; + util.run_regex (regex, data, (res) => { + t.is (res[0], 'foo'); + count++; + }); + t.is (count, 1); +}); + +test ('run non-global regex without result', (t) => { + const data = 'foobarfoo'; + const regex = /baz/u; + let count = 0; + util.run_regex (regex, data, (res) => { + count++; + }); + t.is (count, 0); });