diff --git a/src/lib/builtins/string.rs b/src/lib/builtins/string.rs index 54090f52a0d..4b1343b80d2 100644 --- a/src/lib/builtins/string.rs +++ b/src/lib/builtins/string.rs @@ -744,18 +744,16 @@ pub fn replace(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVal let replacement = get_argument(args, 1); let replacement_str: &str = &ctx.value_to_rust_string(&replacement); - if pattern.is_string() { - let pattern_str: &str = &ctx.value_to_rust_string(&pattern); - // 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 = this_str.replace(pattern_str, replacement_str); - Ok(to_value(result_str)) - } else { - pattern.with_internal_state_ref(|pattern_re: &RegExp| { + if let Some(re_internal_state) = pattern.get_internal_state() { + if let Some(pattern_re) = re_internal_state.downcast_ref::() { let result_str = pattern_re.replace_all(this_str, replacement_str); - Ok(to_value(result_str.into_owned())) - }) + return Ok(to_value(result_str.into_owned())); + } } + + let pattern_str: &str = &ctx.value_to_rust_string(&pattern); + let result_str = this_str.replace(pattern_str, replacement_str); + Ok(to_value(result_str)) } fn get_argument(args: &[Value], idx: usize) -> Value { @@ -1089,6 +1087,7 @@ mod tests { var result1 = str.replace('dog', 'monkey'); var result2 = str.replace('dog.', 'monkey.'); var regexResult = str.replace(/dog./, 'monkey.'); + var intResult = 'abc4e'.replace(4, 'd') var exceptional1 = str.replace(); var exceptional2 = str.replace('dog'); "#; @@ -1097,6 +1096,7 @@ mod tests { assert_eq!(forward(&mut engine, "result1"), "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"); assert_eq!(forward(&mut engine, "result2"), "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"); assert_eq!(forward(&mut engine, "regexResult"), "The quick brown fox jumps over the lazy monkey. If the monkey.reacted, was it really lazy?"); + assert_eq!(forward(&mut engine, "intResult"), "abcde"); assert_eq!( forward(&mut engine, "exceptional1"), "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?"