String.prototype.replace() problems with JSON.stringify() and serialization of Objects

Christoph Martens cmartensms at gmail.com
Mon Jul 28 05:52:56 PDT 2014


Hey everyone,

I wanted to ask if there's a plan to offer something like 
String.prototype.replace(search, replace, stringmode) as an alternative 
API for String.prototype.replace()?


The problem I'm refering here is that the ECMA spec section 15.5.4.11 is 
using the replaceValue as a string that gets parsed (and may contain a $ 
character).
http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.11

So, if you are serializing an Object via toJSON() and want to attach the 
Function.prototype.toString(), the resulting string may contain a $ 
character, even if it is written as a statement. As the 
String.prototype.replace API doesn't offer an option to turn off the 
"parsing" of the replaceValue, I think this is a conceptional flaw in 
the API design.


*Example:*

var func = function() {

   var y = [ 52, '$'];
   return null;

};

var data = func.toString();
var x = 'This is a simple {{blob}}';
var y = x.replace('{{blob}}', data); // Not the expected behaviour 
because of $ character



*Suggestion:*

If you want to replace the string "much simplier" by calling it this 
way, it would save performance and allow you to replace raw strings 
using the simplest way, which is a simple indexOf() and substr().

var data = func.toString(); // Inside an engine, this would be a 
JSON.stringify(environment); or similar
var x = 'This is a simple {{blob}}';
var y = x.replace('{{blob}}', data, true); // note the suggested 
optional flag


An example implementation I made for showing the usage I would prefer:

String.prototype.replace = function(key, value, raw) {

     if (raw === true) {

         var keyl = key.length;
         var keyi = this.indexOf(key);

         return '' + this.substr(0, keyi) + value + this.substr(keyi + 
keyl, this.length - keyl);

     } else {
         // Old behaviour
     }


     return this;

};



What do you guys think about the idea?



PS:

Currently, I have to polyfill a custom method for my build templates in 
my game engine because that API is missing and I think it is pretty 
important to offer.

If you are curious about the use case, it's used for a remote debugger 
and environment snapshots that allows restoring savegames on a different 
computer (NodeJS-sdl or Browser or Server or Android or iOS... etc.). 
Currently the development-0.8 branch, but may merge into master soon: 
https://github.com/LazerUnicorns/lycheeJS/


Cheers,
~Christoph

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140728/f1d4ec33/attachment.html>


More information about the es-discuss mailing list