skip to Main Content

Lets say I have a string with the value "this-is-the-whole-string-value-33297af405e6". I want to extract the last number part from this string. The result I’m looking for is only "33297af405e6". How can I get this value?

2

Answers


  1. For the best performance nothing is faster than searching a string. It could be critical if you process a big JSON data. It’s more than 3x faster that splitting the string:

    const str = 'this-is-the-whole-string-value-33297af405e6';
    const found = str.substring(str.lastIndexOf('-') + 1);
    
    console.log(found);

    And benchmarking different solutions:

    enter image description here

    <script benchmark data-count="10000000">
    
    const str = "this-is-the-whole-string-value-33297af405e6";
    
    // @benchmark split + pop
    
    str.split('-').pop();
    
    // @benchmark split + at
    
    str.split('-').pop();
    
    // @benchmark regex
    
    str.match(/[^-]+$/)[0]
    
    // @benchmark lastIndexOf
    
    str.substring(str.lastIndexOf('-') + 1);
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
  2. split() on -, and get the last part by calling pop() on the array:

    const input = "this-is-the-whole-string-value-33297af405e6";
    
    const output = input.split('-').pop();
    
    console.log(output); // 33297af405e6
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search