我有以下简单的代码:

var S = require('string');

function matchBlacklist(inputString) {
    var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"];
    var found = false;
    for (var i = 0; i < blacklist.length; i++) {

        if (S(inputString).contains(blacklist[i]) > -1) {
            found = true;
        }
    }
    return (found);
}

matchBlacklist("www.facebook.com/this_is_a_test"); // returns true
matchBlacklist("www.example.com/this_is_a_test"); // returns true


但是它总是返回true;因为第二种情况应该返回false

最佳答案

您应该测试if(string.includes(substring)){ ... }而不是if(string.includes(substring) > -1 ){ ... }

但是这里有一个更优雅的单行代码:



const blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"];

const matchBlacklist = inputString => blacklist.some(word => inputString.includes(word))

console.log( matchBlacklist("www.facebook.com/this_is_a_test") ); // returns true
console.log( matchBlacklist("www.example.com/this_is_a_test") ); // returns false

关于javascript - 使用nodeJS在URL中查找子字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49301840/

10-09 22:15