1

I know you can turn a string into an integer using Number and parseInt, but I want to get a number from in the middle or at the end of a string. For example:

'Number 87' --> 87
'data-2384729' --> 2384729
'Beep 8009 Bop' --> 8009

1 Answer 1

2

You can use RegExp together with String#match.

function getNum(str){
  var res = Number(str.match(/\d+/)[0]);
  console.log(res);
}

getNum('Number 87');
getNum('data-2384729');
getNum('Beep 8009 Bop');

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

1 Comment

Note .match() returns an array of strings

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.