mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-14 21:41:23 +00:00
Add bindings for String.prototype.replace
This commit is contained in:
@ -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.
|
||||
///
|
||||
|
@ -1 +1,7 @@
|
||||
exports.new_string_object = () => new String("hi");
|
||||
exports.new_string_object = () => new String("hi");
|
||||
|
||||
exports.get_replacer_function = function() {
|
||||
return function upperToHyphenLower(match, offset, string) {
|
||||
return (offset > 0 ? '-' : '') + match.toLowerCase();
|
||||
};
|
||||
};
|
||||
|
@ -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");
|
||||
|
Reference in New Issue
Block a user