How to calculate the length of msg.payload?

Hi all

I'm struggling with calculate length msg.payload. Is there any way to do it? In addition I want to put 0 in front of msg.payload in case of length of msg.payload is lower than 5 characters. Msg.payload is string.

Thanks for help :slight_smile:

Strings and arrays have a length property.
msg.payload.length will return the string length as an integer

You can also just pad the start of the string if less than x chars.

str.padstart()
msg.payload = msg.payload.padStart(5,"0")

1 Like
var alt_var = msg.payload ;
let msglength = alt_var.length ;

If ( msglength < 5 ) {
msg.payload = "0" + alt_var ;
}

return msg;

This would be a way to do it but best to read up in javascript functions?

1 Like

@E1cid
@znetsixe

Many thanks to you! :slight_smile: both works
When I tried myself to use msg.payload.length I still received original value msg.payload...

Hi to all!
I have this debug as database output:

13/02/2023, 16:21:43[node: debug 22](http://127.0.0.1:1880/#)
SELECT name, lat, lon, type, status FROM stations : msg.payload : Object
object
name: "SIOT"
lat: 43.1339
lon: 11.06825
type: 0
status: 0
13/02/2023, 16:23:57node: debug 22
SELECT name, status FROM stations WHERE name = $stazione : msg.payload : Object
object
name: "BURA"
status: 0

Using msglength = alt_var.length as new payload I always get name: undefined as output.
I need to understand how discriminate between two database output queries....
Thanks,

Your debug suggests that msg.payload is an object.

Try var size = Object.keys(msg.payload).length;
Object.keys() gives you an array ["name", "status"] An array has a length property.