replace() missing

Posted on
  • Hi Gordon,

    The replace() function is missing. This code works on

    var str = "Play with Arduino";
    var res = str.replace("Arduino","Espruino");


  • Thanks. I've just made a bug for this:­ues/334

    Any code contributions welcome ;) For now you can probably work around it by writing your own replace function though.

  • Yes, no problem with that.


  • Hi there,
    For everyone who is also missing the replace function... It took a while for me to find a workaround but one way is to do .split("Arduino") what gives you an array. Than you can loop through this array and add "Espruino" in each loop except the last.
    Best Regards, Andreas

  • You could run this beforehand...

    String.prototype.replace = function(a,b) {
      var i = this.indexOf(a); 
      if (i<0) return this; 
      return this.substr(0,i)+b+this.substr(i+a.lengt­h); 
  • Hi Gordon,

    Too much code, we have to save memory where ever it is possible until an Espruino++ with 96KB is available ;-)

    The split/join method is small:

    'Dear Espruino !'.split('Espruino').join('Gordon'));

    Worked. Returned:

    'Dear Gordon !'

    But there is another bug in split:

    'Dear Espruino'.split('Espruino').join('Gordon­');

    Returns: 'Dear Espruno' and not 'Dear Gordon'

    The reason is that split fails to split the element when it's at the end of the string.

    'Dear Espruino'.split('Espruino') returns

    'Dear Espruino'.split('Espruino');
    =[ "Dear Espruino" ]

    correct is:

    =[ "Dear ", "" ]

    See :­%27.split(%27Espruino%27)%3B


  • Thanks. I'll file a bug for this - I was sure i'd tested for that case though! In the mean time, if you try one of the later builds from Git, String.replace is already implemented.

  • Thanks Gordon, nice to have replace.


  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview

replace() missing

Posted by Avatar for Sacha @Sacha