0

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?

1
  • I would use a RegEx Commented Oct 13, 2022 at 9:32

1 Answer 1

1

An alternative approach to do what you require would be to split() the string by _ and then return the second element of the resulting array:

const getId = str => str.split('_')[1];

['12345_5678', '12345_5678_90', 'abc_5678_multi_sections']
  .forEach(str => console.log(getId(str)));

This assumes there is always at least 1 _ character in the string. If that's not the case then some additional validation logic would need to be implemented.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.