2012-04-04 5 views

Antwort

5
var string = '[United States][Canada][India]'; 
var search = 'Canada'; 
if (string.indexOf('[' + search + ']') !== -1) { 
    // Whatever 
} 
+0

Dies ist der richtige Weg, außer dass Sie das überprüfen sollten "NdexOf" gibt nicht "-1" zurück, andernfalls würde Ihre Prüfung für das erste Element in der Liste fehlschlagen, da es "0" zurückgeben würde. –

+0

@Matt Danke Ihr absolut richtig. Ich wollte eigentlich> -1 qw3n

3

Sie die String-Methoden erweitern ... als Bonus habe ich ein Groß- und Kleinschreibung Spiel

// Only line you really need 
String.prototype.has = function(text) { return this.toLowerCase().indexOf("[" + text.toLowerCase() + "]") != -1; }; 

// As per your example 
var Countries = " [United States] [Canada] [India] "; 

// Check Spain 
if (Countries.has("Spain")) { 
    alert("We got Paella!"); 
} 
// Check Canada 
if (Countries.has("Canada")) { 
    alert("We got canadian girls!"); 
} 
// Check Malformed Canada 
if (Countries.has("cAnAdA")) { 
    alert("We got insensitive cAnAdiAn girls!"); 
} 
// This Check should be false, as it only matches part of a country 
if (Countries.has("Ana")) { 
    alert("We got Ana, bad, bad!"); 
} 

Demo:http://jsfiddle.net/xNGQU/2/

+1

NICE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! –

Verwandte Themen