diff --git a/crates/js-sys/src/lib.rs b/crates/js-sys/src/lib.rs index 75d52cec..6cdc1fdd 100644 --- a/crates/js-sys/src/lib.rs +++ b/crates/js-sys/src/lib.rs @@ -3075,6 +3075,20 @@ extern "C" { #[wasm_bindgen(method, js_class = "String")] pub fn repeat(this: &JsString, count: i32) -> JsString; + /// The replace() method returns a new string with some or all matches of a pattern + /// replaced by a replacement. The pattern can be a string or a RegExp, and + /// the replacement can be a string or a function to be called for each match. + /// + /// Note: The original string will remain unchanged. + /// + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace + #[wasm_bindgen(method, js_class = "String")] + pub fn replace(this: &JsString, pattern: &RegExp, replacement: &str) -> JsString; + + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace + #[wasm_bindgen(method, js_class = "String", js_name = replace)] + pub fn replace_function(this: &JsString, pattern: &RegExp, replacement: &Function) -> JsString; + /// The `slice()` method extracts a section of a string and returns it as a /// new string, without modifying the original string. /// diff --git a/crates/js-sys/tests/wasm/JsString.js b/crates/js-sys/tests/wasm/JsString.js index 04a64a9a..fbaec7ae 100644 --- a/crates/js-sys/tests/wasm/JsString.js +++ b/crates/js-sys/tests/wasm/JsString.js @@ -1 +1,7 @@ -exports.new_string_object = () => new String("hi"); \ No newline at end of file +exports.new_string_object = () => new String("hi"); + +exports.get_replacer_function = function() { + return function upperToHyphenLower(match, offset, string) { + return (offset > 0 ? '-' : '') + match.toLowerCase(); + }; +}; diff --git a/crates/js-sys/tests/wasm/JsString.rs b/crates/js-sys/tests/wasm/JsString.rs index a22fd653..47a3a8fe 100644 --- a/crates/js-sys/tests/wasm/JsString.rs +++ b/crates/js-sys/tests/wasm/JsString.rs @@ -7,6 +7,7 @@ use js_sys::*; #[wasm_bindgen(module = "tests/wasm/JsString.js")] extern { fn new_string_object() -> JsValue; + fn get_replacer_function() -> Function; } #[wasm_bindgen_test] @@ -284,6 +285,21 @@ fn repeat() { assert_eq!(JsString::from("test").repeat(3), "testtesttest"); } +#[wasm_bindgen_test] +fn replace() { + let js = JsString::from("The quick brown fox jumped over the lazy dog. If the dog reacted, was it really lazy?"); + let re = RegExp::new("dog", "g"); + let result = js.replace(&re, "ferret"); + + assert_eq!(result, "The quick brown fox jumped over the lazy ferret. If the ferret reacted, was it really lazy?"); + + let js = JsString::from("borderTop"); + let re = RegExp::new("[A-Z]", "g"); + let result = js.replace_function(&re, &get_replacer_function()); + + assert_eq!(result, "border-top"); +} + #[wasm_bindgen_test] fn slice() { let characters = JsString::from("acxn18");