mirror of
https://github.com/RGBCube/serenity
synced 2025-07-25 15:37:46 +00:00
LibJS: Add the global escape() & unescape() methods
This commit is contained in:
parent
e2fb7943f7
commit
442ef63008
4 changed files with 69 additions and 0 deletions
|
@ -112,6 +112,8 @@ void GlobalObject::initialize_global_object()
|
|||
define_native_function(vm.names.decodeURI, decode_uri, 1, attr);
|
||||
define_native_function(vm.names.encodeURIComponent, encode_uri_component, 1, attr);
|
||||
define_native_function(vm.names.decodeURIComponent, decode_uri_component, 1, attr);
|
||||
define_native_function(vm.names.escape, escape, 1, attr);
|
||||
define_native_function(vm.names.unescape, unescape, 1, attr);
|
||||
|
||||
define_property(vm.names.NaN, js_nan(), 0);
|
||||
define_property(vm.names.Infinity, js_infinity(), 0);
|
||||
|
@ -433,4 +435,46 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::decode_uri_component)
|
|||
return js_string(vm, move(decoded));
|
||||
}
|
||||
|
||||
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::escape)
|
||||
{
|
||||
auto string = vm.argument(0).to_string(global_object);
|
||||
if (vm.exception())
|
||||
return {};
|
||||
StringBuilder escaped;
|
||||
for (auto code_point : Utf8View(string)) {
|
||||
if (code_point < 256) {
|
||||
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./"sv.contains(code_point))
|
||||
escaped.append(code_point);
|
||||
else
|
||||
escaped.appendff("%{:02X}", code_point);
|
||||
continue;
|
||||
}
|
||||
escaped.appendff("%u{:04X}", code_point); // FIXME: Handle utf-16 surrogate pairs
|
||||
}
|
||||
return js_string(vm, escaped.build());
|
||||
}
|
||||
|
||||
JS_DEFINE_NATIVE_FUNCTION(GlobalObject::unescape)
|
||||
{
|
||||
auto string = vm.argument(0).to_string(global_object);
|
||||
if (vm.exception())
|
||||
return {};
|
||||
ssize_t length = string.length();
|
||||
StringBuilder unescaped(length);
|
||||
for (auto k = 0; k < length; ++k) {
|
||||
u32 code_point = string[k];
|
||||
if (code_point == '%') {
|
||||
if (k <= length - 6 && string[k + 1] == 'u' && is_ascii_hex_digit(string[k + 2]) && is_ascii_hex_digit(string[k + 3]) && is_ascii_hex_digit(string[k + 4]) && is_ascii_hex_digit(string[k + 5])) {
|
||||
code_point = (parse_ascii_hex_digit(string[k + 2]) << 12) | (parse_ascii_hex_digit(string[k + 3]) << 8) | (parse_ascii_hex_digit(string[k + 4]) << 4) | parse_ascii_hex_digit(string[k + 5]);
|
||||
k += 5;
|
||||
} else if (k <= length - 3 && is_ascii_hex_digit(string[k + 1]) && is_ascii_hex_digit(string[k + 2])) {
|
||||
code_point = (parse_ascii_hex_digit(string[k + 1]) << 4) | parse_ascii_hex_digit(string[k + 2]);
|
||||
k += 2;
|
||||
}
|
||||
}
|
||||
unescaped.append_code_point(code_point);
|
||||
}
|
||||
return js_string(vm, unescaped.build());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue