Подтвердить что ты не робот

Сравнение строк в Javascript

Допустим, у меня есть массив с множеством названных строк "birdBlue", "birdRed" и некоторыми другими животными, такими как "pig1", "pig2").

Теперь я запускаю цикл for, который проходит через массив и должен возвращать всех птиц. Какое сравнение будет иметь смысл здесь?

Animals == "bird*" была моей первой идеей, но она не работает. Есть ли способ использовать оператор * (или есть что-то похожее на использование?

4b9b3361

Ответ 1

Я думаю, что вы имели в виду что-то вроде "*" (звездочка), например, подстановочный знак:

  • "a * b" => все, что начинается с "a" и заканчивается "b"
  • "a *" => все, что начинается с "a"
  • "* b" => все, что заканчивается на "b"
  • "* a *" => все, что имеет "a" в нем
  • "* a * b *" => все, что имеет "a" в нем, сопровождаемое чем-либо, сопровождаемым "b", сопровождаемым чем-либо

или в вашем примере: "птица *" => все, что начинается с птицы

У меня была похожая проблема, и я написал функцию с 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"
);

Ответ 2

Вы должны использовать RegExp (они потрясающие), легкое решение:

if( /^bird/.test(animals[i]) ){
    // a bird :D
}

Ответ 3

Вы можете использовать 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? = letfly - вы можете использовать этот код, чтобы проверить 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-адреса находится "птица". Например:

var url = 'www.example.com/bird?=fly'

if (url.contains('bird')) {
  // this is true
  // do something
}

Ответ 4

Вот фрагмент кода с поддержкой подстановочных знаков * и ?

let arr = ["birdBlue", "birdRed", "pig1", "pig2" ];
let wild = 'bird*';

let re = new RegExp('^'+wild.replace(/\*/g,'.*').replace(/\?/g,'.')+'$');
let result = arr.filter( x => re.test(x.toLowerCase()) );

console.log(result);

Ответ 5

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 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

Существует длинный список предостережений для метода, подобного этому, и длинный список "what ifs", который не учитывается, некоторые из которых упоминаются в других ответах. Но для простого использования синтаксиса звезды это может быть хорошей отправной точкой.

Fiddle

Ответ 7

Вместо Animals == "bird*" Animals = "bird*" должно работать.