views:

443

answers:

5

How to check if a url or url pattern is presnt or not in a string using javascript.

<script language="javascript">
var str="http://localhost/testprj?test=123213123";
var s=location.href;
if(s.match('/http://localhost/testprj?test=1232/'){
    alert('welcome!!');
}
</script>

what i need is to check the url pattern.

complete code

<html>
<head>
</head>
    <body>
<style>
.active{
    color:#009900;
    font-weight:bold;
}
</style>

    <div id="menu">
    <ul><li>
    <ul><li> <a href="html1.html">0</a>
     <a href="html.html" >1</a>
     <a href="2">2</a>
     </li>
    </ul></li>
    </ul>
    </div>

    <script language="javascript">

     var c=document.getElementById('menu').getElementsByTagName('a').length;
     var v=document.getElementById('menu').getElementsByTagName('a');
     var s=location.href;
     //alert(s.match('html'));
     for(var i=0;i<c;i++){
      //alert('href'+v[i].className);
      if(v[i].href==location.href){
       v[i].className='active';
      }

     }

    </script> 


    </body>
</html>

this is working fine , but if the get params are cause some problms...

like page.php?page=userlist works fine

but

like page.php?page=userlist&id=121221

this is the base link url link

+1  A: 
/http:\/\/localhost\/testprj\?test=1232/.test(s)
Joe Chung
+2  A: 

For pattern checking, you will want to look into regular expressions.

What particular pattern do you want to check for? If you just want to check whether a string is a URL, the following code should do:

var myString = "http://blah.com/helloworld/";
if (myString.match(/http:\/\//)) {
    alert("'myString' is a URL.");
}

Steve

Steve Harrison
A: 

I think you just had some minor syntax issues:

var re = /http:\/\/localhost\/testprj\?test=1232/
var s=location.href;
if(s.match(re)) { 
  alert('welcome!!'); 
}
Matthew Flaschen
/http:\/\/localhost\/testprj\?test=1232/i cant use like this. because , please check my Question i will update
coderex
A: 

note that regular expressions are a data type of their own in javascript: no quotes or anything, just / delimeters

Here Be Wolves
A: 

Yes finaly i got the solution i used the functions

for(var i=0;i<len;i++){
  if(strstr(url,a[i].href)) {
   a[i].className='active';
  }
    }

 function strstr( url, href) {
     var pos = 0;
     url += '';
     pos = url.indexOf( href );
     if (pos == -1) {
         return false;
     } 
     else{
         if(strcmp(url,href)==0)
            return 1;
    }

 }
 function strcmp ( str1, str2 ) {
       return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
 }

like this way, its working fine!!!

Thank you

coderex