Reputation: 81
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
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
Reputation: 397
var outputNumber = example.substring(10);
This is the simple solution because example string always start with 'sorted-by-'.
Upvotes: 3
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
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