diff --git a/src/lib/builtins/string.rs b/src/lib/builtins/string.rs index f8808815219..748b82ababe 100644 --- a/src/lib/builtins/string.rs +++ b/src/lib/builtins/string.rs @@ -4,7 +4,7 @@ use crate::{ object::{Object, ObjectKind, PROTOTYPE}, property::Property, regexp::{make_regexp, match_all as regexp_match_all, r#match as regexp_match}, - value::{from_value, to_value, ResultValue, Value, ValueData}, + value::{from_value, to_value, undefined, ResultValue, Value, ValueData}, }, exec::Interpreter, }; @@ -738,8 +738,13 @@ pub fn replace(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVal let this_str: &str = &ctx.value_to_rust_string(this); // We then do the same thing for the other args // TODO: what if there are missing arguments? - let pattern_str: &str = &ctx.value_to_rust_string(&args[0]); - let replacement_str: &str = &ctx.value_to_rust_string(&args[1]); + let pattern = get_argument(args, 0); + if undefined() == pattern { + return Ok(to_value(this_str)); + } + let replacement = get_argument(args, 1); + let pattern_str: &str = &ctx.value_to_rust_string(&pattern); + let replacement_str: &str = &ctx.value_to_rust_string(&replacement); // The Rust pattern is interpreted as a Regex and replaced in the original string with // the replacement by using Regex.replace_all let result_str = Regex::new(pattern_str) @@ -748,6 +753,13 @@ pub fn replace(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVal Ok(to_value(result_str.into_owned())) } +fn get_argument(args: &[Value], idx: usize) -> Value { + match args.get(idx) { + Some(arg) => arg.clone(), + None => undefined(), + } +} + /// Create a new `String` object pub fn create_constructor(global: &Value) -> Value { // Create constructor function object @@ -1070,9 +1082,16 @@ mod tests { let init = r#" var str = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; var result = str.replace('dog', 'monkey'); + var exceptional1 = str.replace(); + var exceptional2 = str.replace('dog'); "#; forward(&mut engine, init); assert_eq!(forward(&mut engine, "result"), "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"); + assert_eq!( + forward(&mut engine, "exceptional1"), + "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?" + ); + assert_eq!(forward(&mut engine, "exceptional2"), "The quick brown fox jumps over the lazy undefined. If the undefined reacted, was it really lazy?"); } }