4

Have URL'S which has a numeric value in it. Need to extract that numeric value. But the numeric value position is not constant in the URL. Need a generic way how to extract. Can't use the split method because the position of the value is not constant.

For example:

1. https:// www.example.com/A/1234567/B/D?index.html
2. http://www.example.com/A?index.html/pd=1234567
3. http://www.example.com/A/B/C/1234567?index.html

So the above three URL'S has a numeric value whose position is not constant. Can you please provide a generic method where I can get the expected output like "1234567".

5 Answers 5

7

Use a basic regular expression:

"http://www.example.com/A?index.html/pd=1234567".match( /\d+/ );

This returns the first series of numbers in the string. In the above case, we get the following:

[ "1234567" ]
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a fiddle.

$(this).text().match(/\d+/)[0]

Note that this implies that there are no other numeral sequences in the url! No where!

Comments

0

Another working one :)

var str ="https:// www.example.com/A/1234567/B/D?index.html";
var numArray = [];
for (var i = 0, len = str.length; i < len; i++) {
    var character = str[i];
    if(isNumeric(character)){
        numArray.push(character);
    }
}
console.log(numArray);
function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}

Check out the FIDDLE LINK

Comments

0

Adding to @Jonathan, if you want to match all the numeric values then you can use htmlContent.match(/\d+/g)

Comments

0

To scrap a number from the URL is like scraping a number from any string, as long as your link follows the general rule of having the same format every time : meaning just one number. Maybe you will encounter a problem with the port.

This being said you would need to extract the URL : window.location.pathname, so you will get only what is after the "http://example.com:8080" in the URL. Then parse the URL string with a regular expression : urlString.match('[\\d]+');

For example :

function getUrlId(){
  var path  = window.location.pathname;
  var result = path.match('[\\d]+');
  return result[0];   
};

Comments

Your Answer

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