1

Is there an easier way to do this:

    let layer_id = "55-16-A1"
    
    console.log(layer_id.split("-").slice(0,2).join("-"));
// I want: 55-16

I want to get first two parts of id but I only can do it by doing three methods on it which is not an elegant way I think... is there any better way to do this?

Sara Ree
  • 3,417
  • 12
  • 48

3 Answers3

4

You could take the limit parameter of String#split and get only the first two elements from splitting.

let layer_id = "55-16-A1"

console.log(layer_id.split("-", 2).join("-")); // 55-16
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2
  layer_id.slice(0, layer_id.lastIndexOf("-")) // take the part till the last -
  // or, depending on the exact usecase
  layer_id.slice(0, layer_id.indexOf("-", layer_id.indexOf("-"))) // take the string till the second -
  // or
  layer_id.match(/(\d+-\d+)/)[0] // take the first part that matches two groups of one or more chars seperated by a -
  // or
  layer_id.slice(0, 5) // take only the first 5 chars

A bit shorter and possibly slightly more efficient. Not necessarily easier to understand.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    There's also `layer_id.match(/(\d+-\d+)/)[0];` if you wanted to add that as well for completion? – David Thomas Aug 04 '19 at 16:05
  • 1
    You're very welcome, it didn't seem worth adding another answer to 'compete' for votes/acceptance, and wrong to just edit it into your answer without your consent. I would suggest that explain your code, though. That way OP and future visitors can learn, and understand what's going on :) – David Thomas Aug 04 '19 at 16:09
  • @david yup, would've done the same. Also added an explanation (a brief one, but I think it covers everything necessary) – Jonas Wilms Aug 04 '19 at 16:12
1

You can do the split in one step via the substring method but you need the index. If you definitely need the split at the second occurrence of "-" see How to get the nth occurrence in a string?

Otherwise if you are OK with split at the last occurrence:

console.log(layer_id.substring(0, layer_id.lastIndexOf("-"));
Abel
  • 111
  • 4