Check if URL contains number

5

I would like to check if the current URL contains numbers after the #.

I do not need to know if it contains a specific number or a number of numbers, I just need to know if there is any number after #.

EX:

link 123 TRUE

link FALSE

How could I do this?

    
asked by anonymous 29.10.2018 / 21:18

3 answers

8

Capture the hash with location.hash and check that it has a number with .test() using a regular expression \d (number from 0 to 9):

var hash = location.hash;
if(/\d/.test(hash)){
   console.log("tem número");
}else{
   console.log("não tem número");
}

You can use a function for this too:

function verHash(i){
   if(/\d/.test(i)) return true;
   return false;
}

verHash(location.hash);

Then you can assign the value of the function to a variable if you want and check:

var tem_numero = verHash(location.hash);

if(tem_numero){
   console.log("tem número");
}else{
   console.log("não tem número");
}

Or you can check directly on if without declaring a variable if you want:

if(verHash(location.hash)){
   console.log("tem número");
}else{
   console.log("não tem número");
}
  

To verify that the hash contains only numbers (eg, # 123, # 1   etc.) change the regular expression from \d to ^#\d+$ .

    
29.10.2018 / 21:29
3

You can use location.hash to do this verification

if( ! isNaN( location.hash.substr(1) *1 ) )
{
    /// é um numero
}
    
29.10.2018 / 21:22
3

A very simple example:

var valor1 = "https://pt.stackoverflow.com#";
var valor2 = "https://pt.stackoverflow.com#123i";

var verifica1 = valor1.substr(valor1.indexOf("#") + 1);
var verifica2 = valor2.substr(valor2.indexOf("#") + 1);

var encontrou1 = verifica1.match(/\d+/g);
var encontrou2 = verifica2.match(/\d+/g);

alert(encontrou1 != null);
alert(encontrou2 != null);

link

    
29.10.2018 / 21:29