文本文件行与字符串 indexOf() 不匹配

Text file line doesn't match with string indexOf()

如果文本文件中的 link 与当前选项卡 html 中的任何 link 相匹配,我的 Chrome 扩展将显示。文本文件就像-

https://www.facebook.com/groups/929402513755249/
https%3A%2F%2Ficpc.baylor.edu%2F
https%3A%2F%2Fvjudge.net%2Fcontest%2F187074

我的 content.js 是 -

var xhr = new XMLHttpRequest();
        xhr.open('GET', chrome.extension.getURL('file.txt'), true);

        xhr.onreadystatechange = function()
        {
            if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200)
            {
                var allText = xhr.responseText;
                //var lines = allText.split('\n');

                for (var i = 0; i < document.links.length; i++) {
                    var link= document.links[i].href;
                    var lines = allText.split('\n');

                    for(var line = 0; line < lines.length; line++){
                        console.log(link);   // prints: https://www.facebook.com/groups/929402513755249/#
                        console.log(lines[line]);   //prints: https://www.facebook.com/groups/929402513755249/
                        var linestr = lines[line];
                        console.log(link.indexOf(linestr));  // prints: -1
                        console.log(link.indexOf("https://www.facebook.com/groups/929402513755249/") !== -1);  // prints: true
                        if(link.indexOf(lines[line]) !== -1)
                        {
                            console.log("Link Matched!");
                        }
                    }
                }
            }
        };
        xhr.send();

我无法理解为什么 link.indexOf(lines[line]) 是 -1 而 link 是 https://www.facebook.com/groups/929402513755249/# 并且 lines[line]https://www.facebook.com/groups/929402513755249/。但是 link.indexOf("https://www.facebook.com/groups/929402513755249/") returns 0 作为索引。

如果您正在使用 Windows(或至少在 Windows 上编辑文本文件),则行可能由 \r\n 分隔,而不仅仅是 \n ;如果是这种情况,那么所有行都将以 \r 结尾,而链接不会,因此它永远不会匹配。尝试 allText.split(/\r?\n/) 而不是 split('\n').

除了 chridd 的回答之外,还请尝试在查找匹配项之前修剪拆分字符串值,

var linestr = lines[line].trim();