diff --git a/Libraries/LibJS/Runtime/StringPrototype.cpp b/Libraries/LibJS/Runtime/StringPrototype.cpp index 47e48d352c..a798cda9dc 100644 --- a/Libraries/LibJS/Runtime/StringPrototype.cpp +++ b/Libraries/LibJS/Runtime/StringPrototype.cpp @@ -57,6 +57,7 @@ StringPrototype::StringPrototype() put_native_function("trimEnd", trim_end, 0); put_native_function("concat", concat, 1); put_native_function("substring", substring, 2); + put_native_function("includes", includes, 1); } StringPrototype::~StringPrototype() @@ -368,4 +369,32 @@ Value StringPrototype::substring(Interpreter& interpreter) return js_string(interpreter, string_part); } +Value StringPrototype::includes(Interpreter& interpreter) +{ + auto* this_object = interpreter.this_value().to_object(interpreter.heap()); + if (!this_object) + return {}; + + auto& string = this_object->to_string().as_string()->string(); + auto search_string = interpreter.argument(0).to_string(); + i32 position = 0; + + if (interpreter.argument_count() >= 2) { + position = interpreter.argument(1).to_i32(); + + if (position >= static_cast(string.length())) + return Value(false); + + if (position < 0) + position = 0; + } + + if (position == 0) + return Value(string.contains(search_string)); + + auto substring_length = string.length() - position; + auto substring_search = string.substring(position, substring_length); + return Value(substring_search.contains(search_string)); +} + } diff --git a/Libraries/LibJS/Runtime/StringPrototype.h b/Libraries/LibJS/Runtime/StringPrototype.h index 2f2eb9a872..0b0f54ffb1 100644 --- a/Libraries/LibJS/Runtime/StringPrototype.h +++ b/Libraries/LibJS/Runtime/StringPrototype.h @@ -55,6 +55,7 @@ private: static Value trim_start(Interpreter&); static Value trim_end(Interpreter&); static Value concat(Interpreter&); + static Value includes(Interpreter&); }; } diff --git a/Libraries/LibJS/Tests/String.prototype.includes.js b/Libraries/LibJS/Tests/String.prototype.includes.js new file mode 100644 index 0000000000..70da3e7f12 --- /dev/null +++ b/Libraries/LibJS/Tests/String.prototype.includes.js @@ -0,0 +1,18 @@ +load("test-common.js"); + +try { + assert(String.prototype.includes.length === 1); + + assert("hello friends".includes("hello") === true); + assert("hello friends".includes("hello", 100) === false); + assert("hello friends".includes("hello", -10) === true); + assert("hello friends".includes("friends", 6) === true); + assert("hello friends".includes("hello", 6) === false); + assert("hello friends false".includes(false) === true); + assert("hello 10 friends".includes(10) === true); + assert("hello friends undefined".includes() === true); + + console.log("PASS"); +} catch (err) { + console.log("FAIL: " + err); +}