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

Time:08-10

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:

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

Is returning:

3

I'd like it to return:

8177

CodePudding user response:

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

  • Related