Win*_*mez 10 javascript jquery
我有一个字符串数组.我需要找到以键开头的所有字符串.例如:如果['apple','ape','open','soap']
在使用键'ap'搜索时有一个数组 ,我应该只获得'apple'和'ape'而不是'soap'.
这是在javascript中.
Anu*_*rag 15
使用indexOf作为@Annie建议.indexOf用于查找给定字符串中的子字符串.如果没有匹配,则返回-1,否则返回第一个匹配的起始索引.如果该索引是0,则表示匹配在开头.
另一种方法是使用正则表达式.使用^字符从字符串的开头匹配.正则表达式:
/^he/
将匹配所有以字符串开头的字符串"he",例如"hello","hear","helium"等test.RegExp 的方法返回一个布尔值,指示是否存在成功匹配.上述正则表达式可以作为测试/^he/.test("helix")将返回true,而/^he/.test("sheet")不会因为"he"没有在一开始出现.
遍历输入数组中的每个字符串,并收集新数组中匹配的所有字符串(使用indexOf或regex).那个新数组应该包含你想要的东西.
Ann*_*nie 10
function find(key, array) {
// The variable results needs var in this case (without 'var' a global variable is created)
var results = [];
for (var i = 0; i < array.length; i++) {
if (array[i].indexOf(key) == 0) {
results.push(array[i]);
}
}
return results;
}
Run Code Online (Sandbox Code Playgroud)