Get sub string from variable

I Recieved the string “Voeg 45 g pH- toe”. It’s saved in a variable called “PHMessage”

I want to save the numeric value (45) into a number variable

What is the best way to do this?

Inside of an app or in a flow?

Good question flow would be nice but a script is okay to because I run that first setting the value and use it afterwards

You can use the HomeyScript flow card and pass the token with the string as input parameter.

The script can be like this:

return args[0].split(’ ')[1];

args is a input array.
args[0] is your token value.
The text is splitted ad blanks and the second element is returned.

It’s not always on the same position, but always between to words/phrases

If it’s the only number then something like this:
Just a simple loop through the split array. You can use forEach, too.

let array = args[0].split(’ ');
for (let i=0; i<array.length; i++){
  if (typeof array[i] == 'number'){
    return parseFloat(array[i]);
}
throw new Error('No number found');

Just written down and not tested :slight_smile:

This is what regular expressions are used for:

const str   = args[0];
const match = str.match(/\d+/)[0];
if (match) {
  let num = Number(match[0]);
  ...
}

This will find the first number in the string and doesn’t match negative or decimal numbers.

RonnyW - this looks great, but when I try to add it to my HomeScript .split is not recognised. Do I need to install something else to my home to get these commands?

Ignore me please - it is case sensitive and needs a capital ‘S’. Aplogies. I am learning as fast as I can!