Borbat
Borbat

Reputation: 81

Javascript getting number from string

I have a string:

var example = 'sorted-by-' + number;

Where number variable can be any positive integer. I don't know how to reverse this process, not knowing how many digits this number has. I want to get from example string a number at the end.

Upvotes: 0

Views: 93

Answers (5)

Hassan Imam
Hassan Imam

Reputation: 22534

You can also use regex for this.

var number = 245246245;
var example = 'sorted-by-' + number;

var res = example.match(/^sorted-by-(\d+)/);
console.log(+res[1]);

Upvotes: 0

Srichandradeep C
Srichandradeep C

Reputation: 397

var outputNumber = example.substring(10);

This is the simple solution because example string always start with 'sorted-by-'.

Upvotes: 3

Nenad Vracar
Nenad Vracar

Reputation: 122037

You can split string at - and get last element using pop().

var example = 'sorted-by-' + 100.99
var n = +(example.split('-').pop())

console.log(n)

Upvotes: 1

alexmac
alexmac

Reputation: 19597

You can use String#replace function to replace sorted-by- to empty string and after that convert left part to a number:

var example = 'sorted-by-' + 125;
var num = +example.replace('sorted-by-', '');

console.log(num);

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138267

let num = + string.substr(10);

Upvotes: 2

Related Questions