skip to Main Content

I have "Step-1", "Step-2"… etc string.
I want to get only the number. how can i get it ?

My solution:

var stepName = "Step-1";
var stepNumber = Integer.Parse(stepName[5]);

console.log(stepNumber);

but It is not good solution because stepName can be "Step-500".
please suggest me a way to get number after "-"

5

Answers


  1. You can first use match and then use parseInt to get number

    var stepName = "Step-1";
    const match = stepName.match(/d+$/);
    if(match && match.length) {
        const stepNumber = parseInt(match[0], 10)
        console.log(stepNumber);
    }

    You can also use split here as:

    var stepName = "Step-1";
    const splitArr = stepName.split("-")
    const stepNumber = parseInt(splitArr[splitArr.length - 1], 10)
    console.log(stepNumber);

    or

    var stepName = "Step-1";
    const splitArr = stepName.split("-")
    const stepNumber = parseInt(splitArr.at(-1), 10)
    console.log(stepNumber);
    Login or Signup to reply.
  2. var stepName = "Step-1";
    var stepNumber = stepName.split("-");
    
    console.log(stepNumber.length - 1);
    Login or Signup to reply.
  3. You can use this

    var stepName = "Step-1";
    var stepNumber = stepName.split("-")[1];
    
    console.log(Number(stepNumber));
    
    //another example
    var stepName = "Step-500";
    var stepNumber = stepName.split("-")[1];
    
    console.log(Number(stepNumber));
    Login or Signup to reply.
  4. I think the best solution is not by regex. If your text format would be a constant as "Step-1" and your just replacing the number from 1 - 1******** . You can just split them in an array and get the second array.

    let step = "Step-500";
    const stepArray = step.split("-");
    
    document.getElementById("step").innerHTML = stepArray[1];
    <p id="step">
    
    </p>

    So what the code does is it split your string into two and assign it an array

    stepArray[0] = "step"
    stepArray[1] = "500"
    

    PS. But again this will only work if you have a constant format of that variable. e.g "$var1-$var2"

    Login or Signup to reply.
  5. You can do with replace function too, try below code

    var stepName = "Step-1";
    var stepNumber = parseInt(stepName.replace("Step-", ""));
    console.log(stepNumber); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search