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/A/1234567/B/D?index.html
2. .html/pd=1234567
3. .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".
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./A/1234567/B/D?index.html
2. http://www.example./A?index.html/pd=1234567
3. http://www.example./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".
Share Improve this question asked Jun 10, 2015 at 18:00 user4217999user42179995 Answers
Reset to default 7Use a basic regular expression:
"http://www.example./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" ]
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!
Another working one :)
var str ="https:// www.example./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
Adding to @Jonathan, if you want to match all the numeric values then you can use htmlContent.match(/\d+/g)
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.: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];
};