簡體   English   中英

在 Javascript 中搜索一個字符串是否包含 substring(部分搜索)

[英]Search if a string contains a substring in Javascript (partial search)

是的,我知道我們可以使用 indexOf 和 includes 或正則表達式來查找一個字符串是否存在於另一個字符串中。

但是我們有不同的要求。 我們希望 indexOf 或 includes function 返回 true,即使部分字符串匹配而不是整個世界。 讓我舉個例子。

假設我的用戶名是“Animation”。 我輸入的字符串是“sssrtAnimyt5678”。 現在,由於字符串“sssrtAnimyt5678”包含“Animation”中存在的“Anim”,我們希望 function 返回 true。

indexOf、includes 和正則表達式的問題是它試圖找到整個單詞“Animation”,而不是部分單詞“Anim”。 我什至使用了 KMP 算法,發現甚至 KMP 搜索“動畫”而不是“動畫”。 下面是Javascript中KMP的實現。

    var makeKMPTable = function(word) {
    if(Object.prototype.toString.call(word) == '[object String]' ) {
        word = word.split('');
    }
    var results = [];
    var pos = 2;
    var cnd = 0;

    results[0] = -1;
    results[1] = 0;
    while (pos < word.length) {
        if (word[pos - 1] == word[cnd]) {
            cnd++;
            results[pos] = cnd;
            pos++;
        } else if (cnd > 0) {
            cnd = results[cnd];
        } else {
            results[pos] = 0;
            pos++;
        }
    }
    return results;
};

var KMPSearch = function(string, word) {
    if(Object.prototype.toString.call(string) == '[object String]' ) {
        string = string.split('');
    }
    if(Object.prototype.toString.call(word) == '[object String]' ) {
        word = word.split('');
    }

    var index = -1;
    var m = 0;
    var i = 0;
    var T = makeKMPTable(word);

    while (m + i < string.length) {
        if (word[i] == string[m + i]) {
            if (i == word.length - 1) {
                return m;
            }
            i++;
        } else {
            m = m + i - T[i];
            if (T[i] > -1) {
                i = T[i];
            } else {
                i = 0;
            }
        }
    }
    return index;
};
console.log(KMPSearch("sssrtAnimyt5678", "Animation")); // returns -1

所以我想知道這種部分搜索是否可行,如果有人能指出這樣的實現細節或算法,那將會很有幫助。

提前致謝。

只需檢查任何可能的 substring。

 const hasCommon = (a, b) => { for (let i = 0; i < a.length; i++) { for (let j = i + 1; j <= a.length; j++) { if (b.includes(a.slice(i, j))) return true; } } return false; }; console.log(hasCommon('Animation', 'sssrtAnimyt5678'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM