0

I encountered an unexpected behavior of String#replace() method.

const R = S.replace(A, B)

Even if both the A and the B don't include line breaks, but the R and the S has the different number of line breaks.

I tried it on Node.js 6.14.2, 8.11.2, and 10.1.0, on Windows 7. All of those has the same result.

Is this a bug?

Repro: https://github.com/mysticatea/string-replace-unexpected-behavior

mysticatea
  • 1,917
  • 1
  • 12
  • 12
  • Please include a [minimal, working example](https://stackoverflow.com/help/mcve) within your question. [Links are welcomed when providing additional details](https://meta.stackoverflow.com/questions/254428/something-in-my-web-site-or-project-doesnt-work-can-i-just-paste-a-link-to-it), but your posts here should still be able to stand on their own. – Jonathan Lonowski May 20 '18 at 18:47
  • The reason that I separated the repro code is that the repro code includes 10MB string data. Can I include it in this post? – mysticatea May 20 '18 at 19:00
  • No. The link is fine for the full example, but it should also be possible to demonstrate the issue with a smaller set of data (5 lines or less). – Side note: `.replace()` uses the search string as a RegExp pattern. It may be necessary to [escape some characters](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) in `A`. – Jonathan Lonowski May 20 '18 at 19:37
  • For now, I couldn't reproduce it with smaller data. The `a` doesn't include RegExp syntax which matches `\n` (https://github.com/mysticatea/string-replace-unexpected-behavior/blob/master/A.txt). – mysticatea May 20 '18 at 20:26
  • 1
    Another possibility is the [presence of at least `$&` and `$'`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Description) in B.txt. You can [give `.replace()` a function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) to use `B` literally – `S.replace(A, () => B)`. – Jonathan Lonowski May 20 '18 at 20:52
  • Oh, that's it! thank you a lot! – mysticatea May 20 '18 at 20:55

0 Answers0