Skip to content

Commit

Permalink
LibJS: Implement String.prototype.substr according to the spec
Browse files Browse the repository at this point in the history
Fixes SerenityOS#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.
  • Loading branch information
trflynn89 authored and awesomekling committed Apr 15, 2021
1 parent bc9cd55 commit b6093ae
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
31 changes: 17 additions & 14 deletions Userland/Libraries/LibJS/Runtime/StringPrototype.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -424,28 +424,31 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::substr)
return js_string(vm, 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 start = start_argument < 0 ? (string_length - -start_argument) : start_argument;
auto length = vm.argument(1);

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 {};
}
auto int_length = length.is_undefined() ? size : length.to_integer_or_infinity(global_object);
if (vm.exception())
return {};

if (Value(int_start).is_positive_infinity() || (int_length <= 0) || Value(int_length).is_positive_infinity())
return js_string(vm, String(""));

auto int_end = min((i32)(int_start + int_length), size);

if (length == 0)
if (int_start >= int_end)
return js_string(vm, String(""));

auto string_part = string.substring(start, length);
auto string_part = string.substring(int_start, int_end - int_start);
return js_string(vm, string_part);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
test("basic functionality", () => {
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(1)).toBe("ello friends");
expect("hello friends".substr(0, 5)).toBe("hello");
Expand Down

0 comments on commit b6093ae

Please sign in to comment.