0

First:

var s = input_string.replace(/\t/g, '|');

Second:

var s = input_string.split('\t').join('|');

Is there any possibility that they could get different results?

AGamePlayer
  • 7,404
  • 19
  • 62
  • 119
  • 1
    The result will be the same. But in terms of performance replace is far more efficient. Also in terms of readability replace is clear and concise, while split/join is a bit less "direct". I wouldn't recommend the latter by any means unless you have a very specific reason for it. You can read more here https://stackoverflow.com/questions/50463850/split-and-join-function-or-the-replace-function – Daniel Cruz Aug 14 '22 at 02:03
  • Daniel, thanks for the ref. – AGamePlayer Aug 14 '22 at 03:02

1 Answers1

1

Assuming that input_string is a plain string, and that none of the build-in methods String.prototype.replace, String.prototype.split, Array.prototype.join have been tampered with - then no, .replace followed by .join in that matter will always produce the same output.

If you allow for the possibility that the methods have been patched, then all bets are off.

String.prototype.replace = () => '';
console.log('foo'.replace(/\t/g, '|'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320