Skip to content

Commit f8945cb

Browse files
authored
Fix repeated regex.check() calls on the same regex on target javascript (#459)
1 parent 940401f commit f8945cb

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Unreleased
44

5+
- Fixed a bug on target JavaScript where `regex.check` would not correctly execute
6+
while using the same regular expression in consecutive calls.
57
- The `zip` function's second argument in the `list` module gains the `with` label.
68
- The `strict_zip` function's second argument in the `list` module gains the `with` label.
79

src/gleam_stdlib.mjs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,7 @@ export function utf_codepoint_to_int(utf_codepoint) {
371371
}
372372

373373
export function regex_check(regex, string) {
374+
regex.lastIndex = 0;
374375
return regex.test(string);
375376
}
376377

test/gleam/regex_test.gleam

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ pub fn compile_test() {
2727
regex.check(re, "abc\n123")
2828
|> should.be_true
2929

30-
// For Erlang: This test will only passes if unicode and ucp flags are set
30+
// On target Erlang this test will only pass if unicode and ucp flags are set
3131
let assert Ok(re) = regex.compile("\\s", options)
3232
// Em space == U+2003 == " " == used below
3333
regex.check(re, " ")
@@ -42,6 +42,28 @@ pub fn check_test() {
4242

4343
regex.check(re, "boo")
4444
|> should.be_false
45+
46+
re
47+
|> regex.check(content: "foo")
48+
|> should.be_true
49+
50+
"boo"
51+
|> regex.check(with: re)
52+
|> should.be_false
53+
54+
// On target JavaScript internal `RegExp` objects are stateful when they
55+
// have the global or sticky flags set (e.g., /foo/g or /foo/y).
56+
// These following tests make sure that our implementation circumvents this.
57+
let assert Ok(re) = regex.from_string("^-*[0-9]+")
58+
59+
regex.check(re, "1")
60+
|> should.be_true
61+
62+
regex.check(re, "12")
63+
|> should.be_true
64+
65+
regex.check(re, "123")
66+
|> should.be_true
4567
}
4668

4769
pub fn split_test() {

0 commit comments

Comments
 (0)