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.

2

5 Answers 5

3
var outputNumber = example.substring(10);

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

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

Comments

2
let num = + string.substr(10);

Comments

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

Comments

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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.