假设我有一个包含许多字符串的数组,名为“birdBlue”,“birdRed”以及其他一些动物,如“pig1”,“pig2”。
现在我运行一个遍历数组的for循环,并且应该返回所有的鸟。什么比较在这里有意义?
Animals == "bird*"
是我的第一个想法,但不起作用。有没有办法使用运算符*(或者有类似的东西使用?
答案 0 :(得分:74)
我认为你的意思是" *" (星)作为通配符例如:
或在您的示例中:" bird *" =>以鸟为开头的一切
我遇到了类似的问题并用RegExp写了一个函数:
//Short code
function matchRuleShort(str, rule) {
return new RegExp("^" + rule.split("*").join(".*") + "$").test(str);
}
//Explanation code
function matchRuleExpl(str, rule) {
// "." => Find a single character, except newline or line terminator
// ".*" => Matches any string that contains zero or more characters
rule = rule.split("*").join(".*");
// "^" => Matches any string with the following at the beginning of it
// "$" => Matches any string with that in front at the end of it
rule = "^" + rule + "$"
//Create a regular expression object for matching string
var regex = new RegExp(rule);
//Returns true if it finds a match, otherwise it returns false
return regex.test(str);
}
//Examples
alert(
"1. " + matchRuleShort("bird123", "bird*") + "\n" +
"2. " + matchRuleShort("123bird", "*bird") + "\n" +
"3. " + matchRuleShort("123bird123", "*bird*") + "\n" +
"4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +
"5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n"
);

如果您想了解有关所用功能的更多信息:
答案 1 :(得分:8)
你应该使用RegExp(它们很棒)一个简单的解决方案是:
if( /^bird/.test(animals[i]) ){
// a bird :D
}
答案 2 :(得分:3)
使用此“测试”功能,该功能支持*
和?
通配符
function wildTest(wildcard, str) {
const re = new RegExp(`^${wildcard.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
function wildTest(wildcard, str) {
const re = new RegExp(`^${wildcard.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
// Example usage
let arr = ["birdBlue", "birdRed", "pig1", "pig2" ];
let result = arr.filter( x => wildTest('biRd*', x) );
console.log(result);
答案 3 :(得分:2)
您可以使用Javascript的substring方法。例如:
var list = ["bird1", "bird2", "pig1"]
for (var i = 0; i < list.length; i++) {
if (list[i].substring(0,4) == "bird") {
console.log(list[i]);
}
}
哪个输出:
bird1
bird2
基本上,您正在检查数组中的每个项目,以查看前四个字母是否为“鸟”。这确实假设'bird'将始终位于字符串的前面。
因此,假设您从URL获取路径名:
假设您在at bird1?= letsfly - 您可以使用此代码检查网址:
var listOfUrls = [
"bird1?=letsfly",
"bird",
"pigs?=dontfly",
]
for (var i = 0; i < list.length; i++) {
if (listOfUrls[i].substring(0,4) === 'bird') {
// do something
}
}
以上将匹配第一个到URL,但不匹配第三个(不是猪)。您可以轻松地将url.substring(0,4)
替换为正则表达式,或者甚至是其他javascript方法,例如.contains()
使用.contains()
方法可能会更安全一些。您不需要知道URL“bird”的哪个部分。例如:
var url = 'www.example.com/bird?=fly'
if (url.contains('bird')) {
// this is true
// do something
}
答案 4 :(得分:0)
var searchArray = function(arr, str){
// If there are no items in the array, return an empty array
if(typeof arr === 'undefined' || arr.length === 0) return [];
// If the string is empty return all items in the array
if(typeof str === 'undefined' || str.length === 0) return arr;
// Create a new array to hold the results.
var res = [];
// Check where the start (*) is in the string
var starIndex = str.indexOf('*');
// If the star is the first character...
if(starIndex === 0) {
// Get the string without the star.
str = str.substr(1);
for(var i = 0; i < arr.length; i++) {
// Check if each item contains an indexOf function, if it doesn't it's not a (standard) string.
// It doesn't necessarily mean it IS a string either.
if(!arr[i].indexOf) continue;
// Check if the string is at the end of each item.
if(arr[i].indexOf(str) === arr[i].length - str.length) {
// If it is, add the item to the results.
res.push(arr[i]);
}
}
}
// Otherwise, if the star is the last character
else if(starIndex === str.length - 1) {
// Get the string without the star.
str = str.substr(0, str.length - 1);
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is at the beginning of each item
if(arr[i].indexOf(str) === 0) {
// If it is, add the item to the results.
res.push(arr[i]);
}
}
}
// In any other case...
else {
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is anywhere in each item
if(arr[i].indexOf(str) !== -1) {
// If it is, add the item to the results
res.push(arr[i]);
}
}
}
// Return the results as a new array.
return res;
}
var birds = ['bird1','somebird','bird5','bird-big','abird-song'];
var res = searchArray(birds, 'bird*');
// Results: bird1, bird5, bird-big
var res = searchArray(birds, '*bird');
// Results: somebird
var res = searchArray(birds, 'bird');
// Results: bird1, somebird, bird5, bird-big, abird-song
这样的方法有一长串警告,还有一长串没有考虑的“假设”,其中一些在其他答案中有提及。但是对于简单使用星形语法,这可能是一个很好的起点。
答案 5 :(得分:-1)
if(mas[i].indexOf("bird") == 0)
//there is bird
你可以在这里阅读indexOf:http://www.w3schools.com/jsref/jsref_indexof.asp
答案 6 :(得分:-1)
相反,Animals == "bird*"
Animals = "bird*"
应该可以工作。