我想在一个字符串中找到多个子字符串,如果找到所有这三个字符串,那么就这样做,如果没有,则执行其他操作。
我有点坚持如何设置它,以便如果我得到三个" True",我想执行某些事情,其他我希望它做其他事情。
非常感谢。
我的代码如下。
//Main String
var string0 = ' ": {"MATHEMATICS": {"status": "start", "can_start": false}, "READING": {"status": "start", "can_start": false}, "WRITING": {"status": "start", "can_start": false" ';
//Substrings
var substringArray = ['"MATHEMATICS": {"status": "start"', '"READING": {"status": "start"', '"WRITING": {"status": "start"'];
//Check if Substrings are found in MainString
for (l = 0; l < substringArray.length; l++) {
if (string0.indexOf(substringArray[l]) > -1) {
logger.info("True");
} else {
logger.info("False");
}
}
答案 0 :(得分:3)
您可以尝试使用Array.every方法检查所有子字符串。
代码示例:
var isContainsAllTheParts = substringArray.every(function(substring){
return string0.indexOf(substring) >= 0;
});
答案 1 :(得分:0)
只需使用变量来计算&#34; true&#34;
的数量
//Main String
var string0 = ' ": {"MATHEMATICS": {"status": "start", "can_start": false}, "READING": {"status": "start", "can_start": false}, "WRITING": {"status": "start", "can_start": false" ';
//Substrings
var substringArray = ['"MATHEMATICS": {"status": "start"', '"READING": {"status": "start"', '"WRITING": {"status": "start"'];
var matchCount = 0;
//Check if Substrings are found in MainString
for (l = 0; l < substringArray.length; l++) {
if (string0.indexOf(substringArray[l]) > -1) {
logger.info("True");
matchCount++;
} else {
logger.info("False");
}
}
if(matchCount == 3){
//do something
logger.info('I did');
} else {
// do some other thing
logger.info('I did not');
}
&#13;
答案 2 :(得分:0)
我想出了办法。
var magicNumber = 0;
//Check if Substrings are found in string0
for (l = 0; l < substringArray.length; l++) {
//logger.info(substringArray[l]);
if (string0.indexOf(substringArray[l]) > -1) {
logger.info("True");
magicNumber++;
} else {
logger.info("False");
}
}
while (magicNumber < 3) {
//execute this
}
&#13;
答案 3 :(得分:0)
不确定为什么不接受Telman Ahababov的回答。 如果还不清楚的话,我会解释。我也将其缩短一些,并使用更简单的include()方法:
let str = "Here is the string in which we want to find multiple substrings."
let subStrArr = ["Here is", "which we", "multiple"]
let containsAllSubStrs = subStrArr.every(subStr => {
return str.includes(subStr);
});
if (containsAllSubStrs) {
//containsAllSubStrs equals 'true', meaning all substrings were found.
} else {
//containsAllSubStrs equals 'false', meaning NOT all substrings were found.
}