我正在编写一段返回结果为true的JS代码,如果if在字符串中作为子字符串出现(区分大小写),但是如果模式的所有单个字符出现在,则希望扩展其功能以返回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));
我很感激任何指导正确的方向 - 提前感谢你!
答案 0 :(得分:1)
这会告诉您needles
中是否存在haystack
中的所有字符。
var match1 = function(haystack, needles) {
var chars = needles.split('');
for (var i = 0, length = chars.length; i < length; i++) {
if (haystack.indexOf(chars[i]) === -1) {
return false;
}
}
return true;
}
答案 1 :(得分:1)
像这样的函数可以解决这个问题:
function allChars(lookIn, lookFor) {
for(var i = 0; i < lookFor.length; ++i) {
var c = lookFor.charAt(i);
if(lookIn.indexOf(c) == -1)
return false;
}
return true;
}
答案 2 :(得分:1)
实现您期望的解决方案是以下功能:
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()
分开,因此您更容易更改字符的比较方式(具体取决于您是否希望以区分大小写或不区分大小写的方式对它们进行比较)。