[njs] Improved String.prototype.replace().

Alexander Borisov alexander.borisov at nginx.com
Thu May 16 17:19:42 UTC 2019


details:   https://hg.nginx.org/njs/rev/58de3054b28a
branches:  
changeset: 967:58de3054b28a
user:      Alexander Borisov <alexander.borisov at nginx.com>
date:      Tue May 14 13:00:44 2019 +0300
description:
Improved String.prototype.replace().

If replace value is a function and the function return non string
value, then convert returned value to string.

This closes #61 issue on GitHub.

diffstat:

 njs/njs_string.c         |  20 ++++++++++++++------
 njs/test/njs_unit_test.c |   9 +++++++++
 2 files changed, 23 insertions(+), 6 deletions(-)

diffs (57 lines):

diff -r 9005991a53d6 -r 58de3054b28a njs/njs_string.c
--- a/njs/njs_string.c	Wed May 08 17:05:05 2019 +0300
+++ b/njs/njs_string.c	Tue May 14 13:00:44 2019 +0300
@@ -3355,20 +3355,28 @@ static njs_ret_t
 njs_string_replace_search_continuation(njs_vm_t *vm, njs_value_t *args,
     nxt_uint_t nargs, njs_index_t unused)
 {
+    njs_ret_t             ret;
+    njs_value_t           string;
     njs_string_replace_t  *r;
 
     r = njs_vm_continuation(vm);
 
-    if (njs_is_string(&r->retval)) {
-        njs_string_replacement_copy(&r->part[1], &r->retval);
-
-        return njs_string_replace_join(vm, r);
+    if (!njs_is_primitive(&r->retval)) {
+        njs_vm_trap_value(vm, &r->retval);
+        return njs_trap(vm, NJS_TRAP_STRING_ARG);
     }
 
-    njs_internal_error(vm, "unexpected continuation retval type:%s",
+    ret = njs_primitive_value_to_string(vm, &string, &r->retval);
+    if (nxt_slow_path(ret != NJS_OK)) {
+        njs_type_error(vm, "cannot convert primitive value to string: %s",
                        njs_type_string(r->retval.type));
 
-    return NXT_ERROR;
+        return NXT_ERROR;
+    }
+
+    njs_string_replacement_copy(&r->part[1], &string);
+
+    return njs_string_replace_join(vm, r);
 }
 
 
diff -r 9005991a53d6 -r 58de3054b28a njs/test/njs_unit_test.c
--- a/njs/test/njs_unit_test.c	Wed May 08 17:05:05 2019 +0300
+++ b/njs/test/njs_unit_test.c	Tue May 14 13:00:44 2019 +0300
@@ -5484,6 +5484,15 @@ static njs_unit_test_t  njs_test[] =
     { nxt_string("''.replace(/a*/g, '')"),
       nxt_string("") },
 
+    { nxt_string("'12345'.replace(3, () => 0)"),
+      nxt_string("12045") },
+
+    { nxt_string("'123'.replace(3, function() { return {toString: ()=>({})}; })"),
+      nxt_string("TypeError: Cannot convert object to primitive value") },
+
+    { nxt_string("'12345'.replace(3, () => ({toString: () => 'aaaa'}))"),
+      nxt_string("12aaaa45") },
+
     { nxt_string("'abc'.match(/a*/g)"),
       nxt_string("a,,,") },
 


More information about the nginx-devel mailing list