gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:14:05 24 4
gpt4 key购买 nike

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

例如:

这是程序目前所做的:

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 - 如果 pattern 的所有单个字符都出现在 string 中,则返回 true 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com