From a9a1e69f30314c605de7fd511498c31c44e77424 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Mon, 20 Aug 2018 10:42:12 +0200 Subject: [PATCH] feat(js-sys) Implement `String.split` with regexp. --- crates/js-sys/src/lib.rs | 8 ++++++++ crates/js-sys/tests/wasm/JsString.rs | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/crates/js-sys/src/lib.rs b/crates/js-sys/src/lib.rs index 48e7cd30..34484add 100644 --- a/crates/js-sys/src/lib.rs +++ b/crates/js-sys/src/lib.rs @@ -3113,6 +3113,14 @@ extern "C" { #[wasm_bindgen(method, js_class = "String", js_name = split)] pub fn split_limit(this: &JsString, separator: &str, limit: u32) -> Array; + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split + #[wasm_bindgen(method, js_class = "String", js_name = split)] + pub fn split_by_pattern(this: &JsString, pattern: &RegExp) -> Array; + + /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split + #[wasm_bindgen(method, js_class = "String", js_name = split)] + pub fn split_by_pattern_limit(this: &JsString, pattern: &RegExp, limit: u32) -> Array; + /// The `startsWith()` method determines whether a string begins with the /// characters of a specified string, returning true or false as /// appropriate. diff --git a/crates/js-sys/tests/wasm/JsString.rs b/crates/js-sys/tests/wasm/JsString.rs index 5458e3e7..33040966 100644 --- a/crates/js-sys/tests/wasm/JsString.rs +++ b/crates/js-sys/tests/wasm/JsString.rs @@ -352,6 +352,27 @@ fn split() { assert_eq!(result.length(), 2); assert_eq!(v[0], "Oct"); assert_eq!(v[1], "Nov"); + + let js = JsString::from("Oh brave new world"); + let re = RegExp::new("\\s", "g"); + let result = js.split_by_pattern(&re); + + let mut v = Vec::with_capacity(result.length() as usize); + result.for_each(&mut |x, _, _| v.push(x)); + + assert_eq!(v[0], "Oh"); + assert_eq!(v[1], "brave"); + assert_eq!(v[2], "new"); + assert_eq!(v[3], "world"); + + let result = js.split_by_pattern_limit(&re, 2); + + let mut v = Vec::with_capacity(result.length() as usize); + result.for_each(&mut |x, _, _| v.push(x)); + + assert_eq!(result.length(), 2); + assert_eq!(v[0], "Oh"); + assert_eq!(v[1], "brave"); } #[wasm_bindgen_test]