Convert Ordinal String to its number

Viewed 245

I want to Convert Ordinal String to its number e.g

  • "1st" to 1
  • "2nd" to 2
  • "3rd" to 3

...

Tried this function but return its ordinal, not the number

function nth(n){return["st","nd","rd"][((n+90)%100-10)%10-1]||"th"}

it should be the inverse of this function

4 Answers

just use parseInt

console.log(parseInt("1st"))

You can remove the last two characters because suffix has constant length.

function toNum(str) {
  return parseInt(str.substring(0, str.length - 2));
}

console.log(toNum("1st"));

Simply Extract Numerical Values From The String using parseInt()

parseInt("1st");

This will extract 1 i.e. Integer from the String

You can also use the function match(...) with a Regular Expression /[0-9]+/.

console.log("3rd".match(/[0-9]+/)[0]) // -> 3
console.log("52381st".match(/[0-9]+/)[0]) // -> 52381

Just doing "3rd".match(/[0-9]+/) returns an object with a bit of useful data, but just accessing the property [0] will give you the output you're looking for (if you don't want to do parseInt like the other answers are mentioning haha).

Related