1

Possible Duplicate:
JavaScript: string contains

I have a simple question for you. I have a variable with my url. Now i want check this url. I make this javascript:

var url = "http://www.mikevierwind.nl";

if(url == "localhost" ) {
    alert("test");
}

How can i make the follow thing. When mikewind is in variable. Than run it. The variable can also be mikevierwind.be and mikevierwind.eu. But the script must always than run. I must check of mikevierwind is in the variable.

Community
  • 1
  • 1
Mike Vierwind
  • 1,482
  • 4
  • 23
  • 44
  • You just need to check the URL [substring](http://stackoverflow.com/questions/1789945/javascript-string-contains) – Vishal Aug 01 '12 at 13:18

5 Answers5

6
if (url.indexOf("mikevierwind") >= 0 ) {
  alert("test")
}
Christoph
  • 50,121
  • 21
  • 99
  • 128
Vanamali
  • 291
  • 1
  • 6
  • That comparison should really be `!= -1` rather than `> 0`, since the position in the string doesn't matter. – Anthony Grist Aug 01 '12 at 13:18
  • `indexOf()` may return 0 if the string starts with `mikevierwind`. While I appreciate that it shouldn't as a URL, this should be noted for future readers. – Jason McCreary Aug 01 '12 at 13:19
3

If you only care if mikevierwind is in the string, use indexOf()

var url = "http://www.mikevierwind.nl";

if(url.indexOf('mikevierwind') != -1) {
    alert("test");
}
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1

Try the following:

var url = "http://www.mikevierwind.nl";

if(url.indexOf('mikevierwind') != -1) {
    alert("test");
}
Ram
  • 143,282
  • 16
  • 168
  • 197
0

Try this instead of local host

var url = "http://www.mikevierwind.nl";

if(url == document.location.href ) {
    alert("test");
}
Dominic Green
  • 10,142
  • 4
  • 30
  • 34
0
var s = "mikewind.bet";
alert(s.indexOf("mikewind") != -1);
//indexOf returns the position of the string in the other string. If not found, it will return -1.

https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Objects/String/indexOf

var str="This is testing for javascript search !!!";
if(str.search("for") != -1) {
   //logic
} 
Jigar Pandya
  • 6,004
  • 2
  • 27
  • 45