diff --git a/CHANGELOG.md b/CHANGELOG.md index 85ad1a9514..a9a071b1c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ #### :rocket: New Feature - Add optional `message` argument to `Result.getOrThrow` and improve default error message. https://github.com/rescript-lang/rescript/pull/7630 +- Add `RegExp.escape` binding. https://github.com/rescript-lang/rescript/pull/7695 #### :nail_care: Polish diff --git a/runtime/Stdlib_RegExp.res b/runtime/Stdlib_RegExp.res index c371806a83..9f1b5736a2 100644 --- a/runtime/Stdlib_RegExp.res +++ b/runtime/Stdlib_RegExp.res @@ -12,6 +12,8 @@ module Result = { @new external fromString: (string, ~flags: string=?) => t = "RegExp" @new external fromStringWithFlags: (string, ~flags: string) => t = "RegExp" +external escape: string => string = "RegExp.escape" + @send external test: (t, string) => bool = "test" @return(nullable) @send external exec: (t, string) => option = "exec" diff --git a/runtime/Stdlib_RegExp.resi b/runtime/Stdlib_RegExp.resi index fb16a75337..d16a599d10 100644 --- a/runtime/Stdlib_RegExp.resi +++ b/runtime/Stdlib_RegExp.resi @@ -121,6 +121,25 @@ switch regexp->RegExp.exec("ReScript is pretty cool, right?") { @deprecated("Use `fromString` instead") @new external fromStringWithFlags: (string, ~flags: string) => t = "RegExp" +/** +`escape(string)` escapes any potential regex syntax characters in a string. + +See [`RegExp.escape`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/escape) on MDN. + +## Examples +```rescript +let literal = "foo[bar]" +let regexp = literal->RegExp.escape->RegExp.fromString +regexp->RegExp.test("foo[bar]") == true +``` + +## Remark + +Since May 2025, this feature works across the latest devices and browser versions. +This feature might not work in older devices or browsers. +*/ +external escape: string => string = "RegExp.escape" + /** `test(regexp, string)` tests whether the provided `regexp` matches on the provided string. diff --git a/tests/docstring_tests/DocTest.res b/tests/docstring_tests/DocTest.res index feeed50aae..b0bffce3d7 100644 --- a/tests/docstring_tests/DocTest.res +++ b/tests/docstring_tests/DocTest.res @@ -30,6 +30,11 @@ let ignoreRuntimeTests = [ "Stdlib_Set.difference", ], ), + ( + // Ignore tests that require Node.js v24+ + 24, + ["Stdlib_RegExp.escape"], + ), ] let getOutput = buffer => diff --git a/tests/docstring_tests/DocTest.res.js b/tests/docstring_tests/DocTest.res.js index 32c194051a..247e8f3f41 100644 --- a/tests/docstring_tests/DocTest.res.js +++ b/tests/docstring_tests/DocTest.res.js @@ -37,6 +37,10 @@ let ignoreRuntimeTests = [ "Stdlib_Set.symmetricDifference", "Stdlib_Set.difference" ] + ], + [ + 24, + ["Stdlib_RegExp.escape"] ] ];