-1

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 "-"

Toha
  • 5
  • 3

5 Answers5

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);
DecPK
  • 24,537
  • 6
  • 26
  • 42
1

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));
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 11 '23 at 14:18
1

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"

Jhonathan H.
  • 2,734
  • 1
  • 19
  • 28
0

You can do with replace function too, try below code

var stepName = "Step-1";
var stepNumber = parseInt(stepName.replace("Step-", ""));
console.log(stepNumber); 
-1

var stepName = "Step-1";
var stepNumber = stepName.split("-");

console.log(stepNumber.length - 1);