javascript包含方法检查相同的字符串但获得不同的结果

时间:2017-02-13 19:36:50

标签: javascript

我正在尝试使用Javascript' includes()方法在文档中找到文本匹配项。我检查了我的控制台,看看为什么没有返回匹配,并注意到为匹配检查完全相同的字符串返回了不同的结果。我不确定为什么会这样 - 通过一些反复试验,我发现有问题的字符串是the。例如,当我用较长字符串中的the替换参数中的the时,它返回true。有谁知道为什么会这样?

enter image description here

'Whether you call it the restroom, toilet, loo, WC, lavatory, throne, ladies room, commode, lav or bathroom, few phrases are as essential as knowing how to ask where the bathroom facilities are when you’re travelling!'.includes('Whether you call it the')
false
'Whether you call it the restroom, toilet, loo, WC, lavatory, throne, ladies room, commode, lav or bathroom, few phrases are as essential as knowing how to ask where the bathroom facilities are when you’re travelling!'.includes('Whether you call it the')
true

编辑: 我在Google搜索结果页上的点击链接下获取说明文字,并在新页面上查找匹配项。我将描述文本存储在chrome本地存储中,然后遍历新页面中的段落以检查匹配

chrome.storage.local.get("keyName",function(items) {//initialize the application
            console.log(items.keyName)//'Whether you call it the'
            var p = document.getElementsByTagName('p')
            for (n=0;n<p.length;n++){
                console.log(p[n].textContent)//'Whether you call it the restroom, toilet, loo, WC, lavatory, throne, ladies room, commode, lav or bathroom, few phrases are as essential as knowing how to ask where the bathroom facilities are when you’re travelling!'
                if (p[n].textContent.includes(items.keyName)){
                    console.log('found a match at paragraph' + p[n])
                    var newStr = p[n].textContent.replace(items.keyName,"<span style='background-color:yellow'>" + items.keyName + "</span>")
                    p[n].innerHTML=newStr
                    $('html, body').animate({
                    scrollTop: $('p:eq('+n+')').offset().top + 'px'
                    }, 'fast')          
                    return
                }
                else{console.log('no match found')}
            }

})

0 个答案:

没有答案