Search code examples
javascriptjavanashorn

Javascript: replaceAll inside the eval is not working


I have a javascript code inside java nashorn engine eval. Something like this

engine.eval("<code>.... print(printIt.substring(1) + '==>Value:' + obj[property].replaceAll('\n', ' ').....<code>");

Here I want to replace all occurence of \n and \r with simple space. But when I run this I get error:

Exception in thread "main" javax.script.ScriptException: :1:426 Missing close quote


Solution

  • You are making mistake of not escaping the backward slash of \n.

    If you are doing .replaceAll('\n', '<somethng>'), you are literally searching for newline and replacing, which is not equal to searching for \n string.

    Here is how you should do with escaping:

    obj[property].replaceAll('\\n', ' ').replaceAll('\\r', ' ') \\for replacing all newline and carriage return.
    

    On the sidenote: BTW, I am interested in knowing why are you replacing \r it's not much of use doing this as it's not used alone these days very often. Here is the definitions of \r and \n.

    \r = CR (Carriage Return) // Used as a new line character in Mac OS before X

    \n = LF (Line Feed) // Used as a new line character in Unix/Mac OS X

    \r\n = CR + LF // Used as a new line character in Windows