Javascript – checking a pattern present in a string using javascript

javascriptregexurl

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

Best Solution

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