1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 10:57:34 +00:00

LibJS: Implement String.prototype.substr according to the spec

Fixes #6325

The JavaScript on the HTML Spec site that caused the crash is:
    window.location.hash.substr(1)

Of course, window.location.hash can be the empty string. The spec allows
for calling substr(1) on an empty string, but our partial implementation
wasn't handling it properly.
This commit is contained in:
Timothy Flynn 2021-04-14 17:46:18 -04:00 committed by Andreas Kling
parent bc9cd55da4
commit b6093ae2e3
2 changed files with 22 additions and 16 deletions

View file

@ -424,28 +424,31 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::substr)
return js_string(vm, string); return js_string(vm, string);
// FIXME: this should index a UTF-16 code_point view of the string. // FIXME: this should index a UTF-16 code_point view of the string.
auto string_length = (i32)string.length(); auto size = (i32)string.length();
auto start_argument = vm.argument(0).to_i32(global_object); auto int_start = vm.argument(0).to_integer_or_infinity(global_object);
if (vm.exception())
return {};
if (Value(int_start).is_negative_infinity())
int_start = 0;
if (int_start < 0)
int_start = max(size + (i32)int_start, 0);
auto length = vm.argument(1);
auto int_length = length.is_undefined() ? size : length.to_integer_or_infinity(global_object);
if (vm.exception()) if (vm.exception())
return {}; return {};
auto start = start_argument < 0 ? (string_length - -start_argument) : start_argument; if (Value(int_start).is_positive_infinity() || (int_length <= 0) || Value(int_length).is_positive_infinity())
auto length = string_length - start;
if (vm.argument_count() >= 2) {
auto length_argument = vm.argument(1).to_i32(global_object);
if (vm.exception())
return {};
length = max(0, min(length_argument, length));
if (vm.exception())
return {};
}
if (length == 0)
return js_string(vm, String("")); return js_string(vm, String(""));
auto string_part = string.substring(start, length); auto int_end = min((i32)(int_start + int_length), size);
if (int_start >= int_end)
return js_string(vm, String(""));
auto string_part = string.substring(int_start, int_end - int_start);
return js_string(vm, string_part); return js_string(vm, string_part);
} }

View file

@ -1,6 +1,9 @@
test("basic functionality", () => { test("basic functionality", () => {
expect(String.prototype.substr).toHaveLength(2); expect(String.prototype.substr).toHaveLength(2);
expect("".substr(1)).toBe("");
expect("".substr()).toBe("");
expect("".substr(-1)).toBe("");
expect("hello friends".substr()).toBe("hello friends"); expect("hello friends".substr()).toBe("hello friends");
expect("hello friends".substr(1)).toBe("ello friends"); expect("hello friends".substr(1)).toBe("ello friends");
expect("hello friends".substr(0, 5)).toBe("hello"); expect("hello friends".substr(0, 5)).toBe("hello");