Throw TypeError if regex is passed to startsWith, endsWith, includes
@@ -331,11 +331,15 @@ impl String {
// Then we convert it into a Rust String by wrapping it in from_value
let primitive_val = this.to_string(ctx)?;
- // TODO: Should throw TypeError if pattern is regular expression
- let search_string = args
- .get(0)
- .expect("failed to get argument for String method")
- .to_string(ctx)?;
+ let arg = args.get(0).cloned().unwrap_or_else(Value::undefined);
+
+ if Self::is_regexp_object(&arg) {
+ ctx.throw_type_error(
+ "First argument to String.prototype.startsWith must not be a regular expression",
+ )?;
+ }
+
+ let search_string = arg.to_string(ctx)?;
let length = primitive_val.chars().count() as i32;
let search_length = search_string.chars().count() as i32;
@@ -374,11 +378,15 @@ impl String {
// Then we convert it into a Rust String by wrapping it in from_value
let primitive_val = this.to_string(ctx)?;
- // TODO: Should throw TypeError if search_string is regular expression
- let search_string = args
- .get(0)
- .expect("failed to get argument for String method")
- .to_string(ctx)?;
+ let arg = args.get(0).cloned().unwrap_or_else(Value::undefined);
+
+ if Self::is_regexp_object(&arg) {
+ ctx.throw_type_error(
+ "First argument to String.prototype.endsWith must not be a regular expression",
+ )?;
+ }
+
+ let search_string = arg.to_string(ctx)?;
let length = primitive_val.chars().count() as i32;
let search_length = search_string.chars().count() as i32;
@@ -420,11 +428,15 @@ impl String {
// Then we convert it into a Rust String by wrapping it in from_value
let primitive_val = this.to_string(ctx)?;
- // TODO: Should throw TypeError if search_string is regular expression
- let search_string = args
- .get(0)
- .expect("failed to get argument for String method")
- .to_string(ctx)?;
+ let arg = args.get(0).cloned().unwrap_or_else(Value::undefined);
+
+ if Self::is_regexp_object(&arg) {
+ ctx.throw_type_error(
+ "First argument to String.prototype.includes must not be a regular expression",
+ )?;
+ }
+
+ let search_string = arg.to_string(ctx)?;
let length = primitive_val.chars().count() as i32;
@@ -462,6 +474,13 @@ impl String {
}
}
+ fn is_regexp_object(value: &Value) -> bool {
+ match value {
+ Value::Object(ref obj) => obj.borrow().is_regexp(),
+ _ => false,
+ }
+ }
+
/// `String.prototype.replace( regexp|substr, newSubstr|function )`
///
/// The `replace()` method returns a new string with some or all matches of a `pattern` replaced by a `replacement`.
