javascript - 如果模式的所有单个字符都出现在字符串中,则返回 true 结果

标签 javascript

我正在编写一段 JS 代码,如果模式作为子字符串(区分大小写)出现在字符串中,则返回 true 结果,但希望扩展其功能以在模式的所有单个字符出现在字符串(无论顺序)。

例如:

这就是该程序当前所做的事情:

match1("adipisci","pis") returns true

而我现在希望它这样做:

match1("adipisci","sciip") returns true
match2("adipisci","sciipx") returns false because x does not exist in variable

我在将其实现到我的代码中时遇到困难:

var pages=[
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
  "Nulla imperdiet laoreet neque.",
  "Praesent at gravida nisl. Quisque tincidunt, est ac porta malesuada, augue lorem posuere lacus, vitae commodo purus nunc et lacus."
  ];
var search_term = prompt('Type in search term: ','Search word');
// ask which search term the user wants to search for with default being 'Search Term' 
function find_s(w) {
    var indexes = [0,0,0] // create an array  to hold pages where search term found
    var iii = 0 // create variable to increment the number of finds in each page
    for (var ii=0;ii<pages.length;ii++) {
    // for each page in the array
        for (var i=0;i<pages[ii].length;i++) {
        // for each character in the chosen page
            if (pages[ii].substr(i,w.length).toLowerCase()==w.substr(0,w.length).toLowerCase()) {
            // check to see if the search term is there ignoring case
                iii++;
                // increment number of times the search term in found
                while(pages[ii].substr(i,1)!=" ") {
                    // move to the next word but checking for spaces
                    i++;
                    }
            }
        }
        indexes[ii]=iii;
        // update the number of times the search term is found in that page
        iii=0;
        // reset counter for next page search
    }
    return (w + " was found in this may times in each page " + indexes);
    // let the user know the result
}
alert (find_s(search_term));

如果您能提供正确方向的指导,我将不胜感激 - 提前感谢您!

最佳答案

实现您期望的解决方案是以下函数:

var containsChars = function(where, what){
    var containsChar = function(where, what){
        return !!(where.indexOf(what)+1);
    }    
    var allChars = what.split('');
    for (var i=0; i<allChars.length; i++){
        if (!containsChar(where, allChars[i])){
            return false;
        }
    }
    return true;
}

作为证明,请参阅 this jsfiddle .

我有意将函数 containsChar() 分开,这样您就可以更轻松地更改字符的比较方式(取决于您希望以区分大小写还是不区分大小写的方式比较它们)。

关于javascript - 如果模式的所有单个字符都出现在字符串中,则返回 true 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988989/

相关文章:

javascript - Node JS - 如何调用 "module.export"函数内的方法?

javascript - ExtJS 3.4 - 组合框链接

javascript - NodeJs : How to use a Promise across multiple files?

javascript - IE 10 不支持 dragover 和 drop 事件

javascript - Spring MVC中如何实现AJAX?

Javascript 将文本添加到文档头部

javascript - Unity3D 播放器尺寸变化?

linux - 使用 Javascript 运行远程命令

javascript - Service Worker 忽略获取缓存设置

javascript - css width 浏览器特定方式