I have different versions of id's that I need to loop over and return part of a substring.
Example 1: 12345_5678
Example 2: 12345_5678_90
I want to return the "5678" part of both strings. So far I have the following code:
//let str = '12345_5678';
let str = '12345_5678_90';
let subStr = str.slice(
str.indexOf('_') + 1,
str.lastIndexOf('_'),
);
console.log(subStr);
For the string with "12345_5678_90" the "5678" part gets returned correct but for the "12345_5678" string it returns empty because I dont have the second "_". How can I write a statement that would cover both cases?
Would I need to check if the string contains 1 or 2 "_" before processing the substring?