假设我有一个包含许多 Strings Called 的数组"birdBlue"
,"birdRed"
以及一些其他的动物,如"pig1"
, "pig2"
)。
现在我运行一个遍历数组的 for 循环,应该返回所有的鸟。什么比较在这里有意义?
Animals == "bird*"
是我的第一个想法,但不起作用。有没有办法使用运算符 * (或者是否有类似的用法?
假设我有一个包含许多 Strings Called 的数组"birdBlue"
,"birdRed"
以及一些其他的动物,如"pig1"
, "pig2"
)。
现在我运行一个遍历数组的 for 循环,应该返回所有的鸟。什么比较在这里有意义?
Animals == "bird*"
是我的第一个想法,但不起作用。有没有办法使用运算符 * (或者是否有类似的用法?
我认为您的意思是“*”(星号)作为通配符,例如:
或在您的示例中:“bird*” => 以bird 开头的所有内容
我遇到了类似的问题,并用 RegExp 编写了一个函数:
//Short code
function matchRuleShort(str, rule) {
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);
}
//Explanation code
function matchRuleExpl(str, rule) {
// for this solution to work on any string, no matter what characters it has
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
// "." => Find a single character, except newline or line terminator
// ".*" => Matches any string that contains zero or more characters
rule = rule.split("*").map(escapeRegex).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" +
"6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +
"7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"
);
如果您想阅读有关所用函数的更多信息:
您应该使用 RegExp(它们很棒)一个简单的解决方案是:
if( /^bird/.test(animals[i]) ){
// a bird :D
}
此函数将通配符转换为正则表达式并进行测试(它支持.
和通配符*
)
function wildTest(wildcard, str) {
let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
您可以使用 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
基本上,您正在检查数组中的每个项目以查看前四个字母是否为“鸟”。这确实假设“鸟”将始终位于字符串的前面。
因此,假设您从 URL 获取路径名:
假设您在 Bird1?=letsfly - 您可以使用此代码检查 URL:
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
}
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
像这样的方法有一长串警告,还有一长串没有考虑的“假设”,其中一些在其他答案中提到。但是对于星形语法的简单使用,这可能是一个很好的起点。