【发布时间】:2017-10-01 00:27:16
【问题描述】:
是否可以在 javascript 的 indexOf 方法中使用部分/子字符串匹配?
我有一个字符串数组列表,我想在 indexOf 方法中使用完整字符串的部分文本来获取数组列表中所需字符串的索引号。
var text[]=
0----This text over here $%*&*&*&(()(&$..: matches
1----%#@!$%*&*&*&(()(&$..: text to be matched
2----Where does this %#@!$%*&*&*&(()(&$..: belongs to any type of category
3----There are many %#@!$%*&*&*&(()(&$..: comparators
var index=text.indexOf("Where does this %#@!$%*&*&*&(()(&$..: belongs to any type of category"),
而不是上面的行,我想使用类似的东西:
var index=text.indexOf("belongs to any type of category")
我需要根据文本匹配获得索引号 2,即“这个 %#@!$%&&*&(()(&$..: 属于任何类别类型" 但是字符串中的特殊字符的 bcz 使它变得凝灰 & 因为它的数组具有我动态获取的其他字符串,这增加了复杂性。
所以我正在尝试使用 .indexOf 方法,我们可以在其中传递一个字符串并返回索引号,所以我的问题是有一种方法可以传递字符串的一部分而不是整个字符串并获取索引号 2 成功了吗?
代码尝试:
describe('angularjs homepage todo list', function() {
var index = 'not found';
var text1 = "";
it('test', function() {
var textToFind = "belongs to any type of category";
for (var i=0;i<10;i++){
var results_list=element.all(By.xpath("//*[@id='panel']/div/div[2]/span[1]")).get(i).getText().then(function(text) {
text1=text1+"\n"+text;
console.log("promise returned text inside function is "+text1);
return text1;
})
}
console.log('Text via global defined variable text1 is ' + text1);
getIndex(0, text1.length, text1, textToFind);
console.log('index is ' + index);
});
function getIndex(i, max, array, textToFind) {
if (i < max) {
console.log('text[' + i + '].indexOf = ' + array[i].indexOf(textToFind))
if (array[i].indexOf(textToFind) > 0) {
index = i;
//The index number will be assigned to the variable index
//if indexOf is greater than 0, e.g. 38 was returned on index 2
} else {
getIndex(i + 1, max, array, textToFind);
}
}
}
});
Started
Started execution of test
Text via global defined variable text1 is
index is not found
Test Case passed
promise returned text inside function is ['This text over here $%*&*&*&(()(&$..: matches',
'%#@!$%*&*&*&(()(&$..: text to be matched',
'Where does this %#@!$%*&*&*&(()(&$..: belongs to any type of category',
'There are many %#@!$%*&*&*&(()(&$..: comparators']
1 spec, 0 failures
Finished in 58.462 seconds
[18:35:47] I/launcher - 0 instance(s) of WebDriver still running
[18:35:47] I/launcher - internet explorerANY #01 passed
【问题讨论】:
-
这不是一个普通的单行字符串......它是一个字符串数组,当使用 indexOf 方法完成比较时,它会获取相应索引的全部值。
-
请说明您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。
-
stackoverflow.com/questions/5424488/… 看看这个和你问的一样
标签: javascript automation protractor substring