Mikkel Fennefoss
Mikkel Fennefoss

Reputation: 911

Get substring between characters or after first occurrence of character

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?

Upvotes: 0

Views: 35

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

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.

Upvotes: 1

Related Questions