Contains a sub string does not work

Hello,
I ve this payload:
"Relay Off 4C:11:AE:0D:4B:48"
I want to use a function node to check if the string contains "On" or "Off" and this is my function which doesnt work. pls help:

if (msg.payload.contains == "Off")
{
    msg.payload = "Light Off";
    return msg;
}
if (msg.payload.contains == "On")
{
    msg.payload = "Light On";
    return msg;
}
return null;

I tried "msg.payload.contains("Off")" with double and single quotes ...
Can someone help ? thx!

In JavaScript there is no contains function available on the String object. Instead you can use String.includes:

if (msg.payload.includes("Off"))
{
   ...
}

MDN provides a useful reference of the available functions on Strings - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

1 Like

Aha okay ! Thx ... in this case I am wondering why the "contains" keyword is accepted by the editor.

Because the editor isn't doing full type-aware syntax validation. It doesn't know what type of thing msg.payload is, so it doesn't know what properties exist.

As a line of code:

if (msg.payload.contains("Off")) {

is perfectly valid JavaScript syntax. msg.payload might be an object that has a contains function. It is only when it runs the code will it know if that function exists or not.