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

1
  • Split by '-' and take the second element (stepName.split('-')[1]) or make a slice (stepName.slice(5)). Commented Jun 11, 2023 at 7:42

5 Answers 5

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);

Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

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));

1 Comment

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.
0

You can do with replace function too, try below code

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

Comments

-1

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

console.log(stepNumber.length - 1);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.