Skip to content

Commit

Permalink
String.replace: avoid interpreting string as regex
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagoarrais committed Oct 31, 2019
1 parent 2c0add9 commit a540bd7
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/lib/builtins/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use crate::{
exec::Interpreter,
};
use gc::Gc;
use regex::Regex;
use std::{
cmp::{max, min},
f64::NAN,
Expand Down Expand Up @@ -747,10 +746,8 @@ pub fn replace(this: &Value, args: &[Value], ctx: &mut Interpreter) -> ResultVal
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)
.unwrap()
.replace_all(this_str, replacement_str);
Ok(to_value(result_str.into_owned()))
let result_str = this_str.replace(pattern_str, replacement_str);
Ok(to_value(result_str))
}

fn get_argument(args: &[Value], idx: usize) -> Value {
Expand Down Expand Up @@ -1081,17 +1078,20 @@ mod tests {
let mut engine = Executor::new(realm);
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 result1 = str.replace('dog', 'monkey');
var result2 = 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, "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, "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?");
assert_eq!(forward(&mut engine, "exceptional2"), "The quick brown fox jumps over the lazy undefined. If the undefined reacted, was it really lazy?");
}
}

0 comments on commit a540bd7

Please sign in to comment.