How to extract only numeric value only from javascript or jquery url

Has a URL that has a numerical value in it. It is necessary to extract this numerical value. But the position of the numeric value is not constant in the url. Need a general way to extract. You cannot use the split method because the position of the value is not constant.

For instance:

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

Thus, the above three URLs have a numeric value whose position is not constant. Can you provide a general method in which I can get the expected result, for example "1234567".

+4
source share
5 answers

Use a basic regex:

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

. :

[ "1234567" ]
+6

fiddle.

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

, , URL ! , !

+1

:)

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)
}

FIDDLE LINK

+1

@Jonathan, , htmlContent.match(/\d+/g)

+1

URL-, , : . , .

In doing so, you need to extract the URL: window.location.pathnameso you only get what is after " http://example.com:8080 " in the URL. Then parse the regex URL string:urlString.match('[\\d]+');

For instance:

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

All Articles