Split String only on last seperator

Hi,
I have items with different amount of Seperators “_” in the Itemname.
Example:

Fenster_Badezimmer_Nord_Links_Zustand
Fenster_Badezimmer_Nord_Links_LetztesUpdate

Fenster_Badezimmer_Nord_Rechts_Zustand
Fenster_Badezimmer_Nord_Rechts_LetztesUpdate

Fenster_Duschbad_Nord_Zustand
Fenster_Duschbad_Nord_LetztesUpdate

Now I have a widget with an oh-repeater component and would like have the string before the parameter Zustand to then get the fitting Element for LetztesUpdate.
But because the items have a different amount of seperators (“_”), which I need in this case, I can’t use my normal method to build the string via:

items[loop.item.name.split("_")[0]+"_"+items[loop.item.name.split("_")[1]+ "_LetztesUpdate"].state

Is there any possibility to split the loop.item.name only on the last “_”?

There are lots of ways but I usually carefully name my Items to avoid this situation.

val i = item.name.lastIndexOf(c); 
val beforePart = item.name.substring(0, i)

There are a couple of ways to achieve this:

If you know that the starting item will always end in _Zustand then you can just use the string method slice to remove the last 8 characters of the string:

loop.item.name.slice(0,-8)

If you have variable length suffixes on the item name then you can use split and then slice the last element off of the array and re-merge the elements with join:

loop.item.name.split("_").slice(0,-1).join("_")

You can also use lastIndexOf as in @rlkoshak’s answer, but there is no assignment in widget expressions so you’d have to combine that into one expression:

loop.item.name.substring(0, loop.item.name.lastIndexOf('_'))
1 Like

I missed this was about widgets and not rules.

Thanks a lot for this great answer and clear examples!