Saturday, June 28, 2008

Search a String JavaScript - (Like strstr in php)

you want to search a keyword(String) within a given String using Javascript? need a function like strstr() in php? Then you should look at this code, like in php I haven't seen a built in function to do this but by using some regular expression you can accomplish this task

<script type="text/javascript">
//visit kuppiya.com
var myKey = /kuppiya/;
var myStringVar = "I Love kuppiya";
var myMatch = myStringVar.search(myKey);
if(myMatch != -1)
{
alert("Wow There is a match "); 
}
else
{
alert("hmmm no match");
} 
</script>



Get custom programming done at GetAFreelancer.com!

4 comments:

  1. Thank you!
    I just used it and it works :)
    Yeeepeeee... \o/

    ReplyDelete
  2. Works for me as well nice one!!

    ReplyDelete
  3. o/

    build-in function: 'indexOf' does the job, without regex so workin' faster than your solution. returns the nbr of occurs in the string and -1 if no matches were found

    ReplyDelete