Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8164708

String.prototype.replace replaces empty match twice

    XMLWordPrintable

Details

    • b142
    • generic
    • generic

    Description

      FULL PRODUCT VERSION :
      java version "1.8.0_101"
      Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
      Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

      ADDITIONAL OS VERSION INFORMATION :
      OSX El Capitan - version 10.11.6

      uname -a
      Darwin SDGL149ca5171.local 15.6.0 Darwin Kernel Version 15.6.0: Thu Jun 23 18:25:34 PDT 2016; root:xnu-3248.60.10~1/RELEASE_X86_64 x86_64

      A DESCRIPTION OF THE PROBLEM :
      Regex replacement using Nashorn has different behavior than other javascript implementations.



      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Open up the `jjs` shell, and get the output of the following command:

      "4005".replace(/\B(?=(\d{3})+(?!\d))/g, ",");

      The output for nashorn is: "4,,005". Note the duplicate comma.

      In the Rhino ScriptEngine, NodeJS, or any browser implementation of Javascript, the double comma doesn't exist.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      I would expect the output of the .replace() to be equal to "4,005", as it is in every other Javascript implementation.
      ACTUAL -
      The output of the replace contains a duplicate ","

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
          public static void main(String[] args) throws ScriptException {
              ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("js");
              String replaceResult = (String) scriptEngine.eval("\"4005\".replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\")");
              if (!replaceResult.equals("4,005")) {
                  throw new RuntimeException("Replace failed");
              }
          }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      You can switch to use the Rhino ScriptEngine, which doesn't contain this error.


      ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("rhino");

      Add this dependency if using maven:
              <dependency>
                  <groupId>de.christophkraemer</groupId>
                  <artifactId>rhino-script-engine</artifactId>
                  <version>1.1.0</version>
              </dependency>

      Attachments

        Issue Links

          Activity

            People

              hannesw Hannes Wallnoefer
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: