Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function to return digits from a string, if length >= 4

This function is retrieving the last numbers of a string:

function getLastNumberOfString(str){
  var allNumbers = str.replace(/[^0-9]/g, ' ').trim().split(/\s+/);
  return parseInt(allNumbers[allNumbers.length - 1], 10);
}

I want it to retrieve the last numbers of a string, if it contains at least 4 digits.

For example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"1234-string-text/8177-1-3-tools-for-knowledge.html"

Is returning:

3

I’d like it to return:

8177

>Solution :

To match last set of numbers containing at least 4 digits use:

\d{4,}(?!.+\d{4})

RegEx Demo

RegEx Details:

  • \d{4,}: Match 4 or more digits
  • (?!.+\d{4}): Negative Lookahead to assert that there is no other occurrence of 4 digit numbers ahead

Code:

function getLastNumberOfString(str){
  var m = str.match(/\d{4,}(?!.+\d{4})/);
  return (m ? parseInt(m[0]) : NaN);
}

console.log(getLastNumberOfString("1234-string-text/8177-1-3-tools-for-knowledge.html"));

console.log(getLastNumberOfString("tools-for-knowledge.html"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading