【问题标题】:Text file line doesn't match with string indexOf()文本文件行与字符串 indexOf() 不匹配
【发布时间】:2018-03-06 21:22:00
【问题描述】:

我的 Chrome 扩展程序将显示文本文件中的链接是否与当前选项卡的 html 中的任何链接匹配。文本文件就像 -

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();

当链接为https://www.facebook.com/groups/929402513755249/#lines[line]https://www.facebook.com/groups/929402513755249/ 时,我不明白为什么link.indexOf(lines[line]) 为-1。但是link.indexOf("https://www.facebook.com/groups/929402513755249/") 返回 0 作为索引。

【问题讨论】:

    标签: javascript string file google-chrome-extension indexof


    【解决方案1】:

    除了chridd的回答,还可以在寻找匹配之前尝试修剪分割的字符串值,

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-13
        • 2020-06-17
        • 1970-01-01
        • 1970-01-01
        • 2011-02-09
        • 2015-01-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多