trim last character from string?

Posted on
  • I read through the reference section of this website and could not find a trim or some sort of replace function. The issue I am having is, my PH sensor responds with a float(ie 8.55) with a length of 5. I think the fifth character is a carriage return. I could not tell so I used String.charCodeAt(5) which responded back with a 13. How do I remove the \r or any none digit character from the end of the float value? Since the value is sent via serial communication I tried:

    If (e.data != "\r" || e.data != "\n") {
      phValue = e.data;
    }
    

    However, when I check the length of the phValue again I am still getting a length of 5.

  • I did:

    phValue = phValue.substring(0, phValue.length - 1);
    

    That code removes the last character as expected.

    In my previous forum post I explained that I attempted to catch the \r by doing:

    if (e.data != "\r" || e.data != "\n") {
          console.log("NO CR");
          phValue+=e.data;
        }
    

    However, "NO CR" is echoing out 5 times instead of only 4. I have no idea why \r is getting stored to the phValue when the if statement I think should of filtered \r out. Can anyone explain why this is happening?

  • I started from scratch and removed the line:

    phValue = phValue.substring(0, phValue.length - 1);
    

    Everything seems to be working properly. I have no idea why, but starting from scratch seemed to do the trick.

  • I think your issue was e.data != "\r" || e.data != "\n" because it'll always be true - it should be e.data != "\r" && e.data != "\n"

    I guess the thing to do is to use the \r as a signal that the data has ended:

    if (e.data == "\r" || e.data == "\n") {
      print(myValue);
      myValue="";
    } else {
      myValue+=e.data;
    }
    
  • e.data != "\r" || e.data != "\n"
    

    That was exactly the issue. I read the sensor module user guide again, it explained the results will end in a "\r". So I removed the checking for the newline character. As soon as I removed the newline check and only checked for a CR:

    if (e.data != "\r")
    

    It worked. When I get home from work I will implement your example.

  • If the value is actually a floating point number, but you're receiving a string, then you should be able to simply coerce the value to a number and the non-numeric characters will be discarded:

    var ph = "8.55\r\n";
    
    +ph === 8.55; // true
    

    Unfortunately, that doesn't seem to work correctly in Espruino. I've filed a bug: https://github.com/espruino/Espruino/iss­ues/268

  • Fixed now ;)

  • claps

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

trim last character from string?

Posted by Avatar for d0773d @d0773d

Actions