From a2e734d202e10ec9ef61095bf2e05f634873d441 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Fri, 16 Jul 2021 13:04:46 -0400 Subject: [PATCH] LibJS: Report string length as the code point length, not byte length For example, U+180E is 3 bytes, but should have a string length of 1. --- Userland/Libraries/LibJS/Runtime/StringObject.cpp | 3 ++- Userland/Libraries/LibJS/Tests/builtins/String/String.js | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Userland/Libraries/LibJS/Runtime/StringObject.cpp b/Userland/Libraries/LibJS/Runtime/StringObject.cpp index a1f4186c4c..a941744060 100644 --- a/Userland/Libraries/LibJS/Runtime/StringObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringObject.cpp @@ -5,6 +5,7 @@ * SPDX-License-Identifier: BSD-2-Clause */ +#include #include #include #include @@ -33,7 +34,7 @@ void StringObject::initialize(GlobalObject& global_object) { auto& vm = this->vm(); Object::initialize(global_object); - define_direct_property(vm.names.length, Value(m_string.string().length()), 0); + define_direct_property(vm.names.length, Value(Utf8View(m_string.string()).length()), 0); } void StringObject::visit_edges(Cell::Visitor& visitor) diff --git a/Userland/Libraries/LibJS/Tests/builtins/String/String.js b/Userland/Libraries/LibJS/Tests/builtins/String/String.js index 687e0929d4..ba076bd5b4 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/String/String.js +++ b/Userland/Libraries/LibJS/Tests/builtins/String/String.js @@ -7,3 +7,10 @@ test("typeof", () => { expect(typeof String()).toBe("string"); expect(typeof new String()).toBe("object"); }); + +test("length", () => { + expect(new String().length).toBe(0); + expect(new String("a").length).toBe(1); + expect(new String("\u180E").length).toBe(1); + expect(new String("\uDBFF\uDFFF").length).toBe(2); +});