0

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.

Borbat
  • 81
  • 1
  • 9
  • 3
    Possible duplicate of [JavaScript get number from string](https://stackoverflow.com/questions/10003683/javascript-get-number-from-string) – M0ns1f Aug 27 '17 at 11:24
  • You question is deplicate see this https://stackoverflow.com/questions/10003683/javascript-get-number-from-string – M0ns1f Aug 27 '17 at 11:25

5 Answers5

3
var outputNumber = example.substring(10);

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

Srichandradeep C
  • 387
  • 2
  • 13
2
let num = + string.substr(10);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

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);
alexmac
  • 19,087
  • 7
  • 58
  • 69
1

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

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]);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51