我正在尝试编写一个函数,如果在该字符串中找到某个模式,它将打印部分字符串。
我有一个包含以下内容的字符串数组:
pages = ["|stackoverflow.com| The website serves as a platform for users to ask and answer questions." , "|reddit.com| A social news aggregation, web content rating, and discussion website"]
当用户输入urlReturn(pages,"platform")
时,该功能应输出stackoverflow.com
我试过但无济于事,非常感谢帮助!
答案 0 :(得分:0)
var urlReturn = (pages, text) => pages.filter(page => page.indexOf(text) > -1).map(page => /\|([^|]*)\|/.exec(page)[1])
我建议你在MDN中查找这些内容。关于正则表达和集合,有几篇好文章/文档。
答案 1 :(得分:0)
for (idx in pages) {
if (pages[idx].indexOf('platform') != -1) {
console.log(pages[idx].substr(1, pages[idx].indexOf('|', 1) - 1))
}
}
答案 2 :(得分:0)
以下代码段可以帮助您覆盖多个结果:
pages = ["|stackoverflow.com| The website serves as a platform for users to ask and answer questions.",
"|reddit.com| A social news aggregation, web content rating, and discussion website",
"|lorem.com| Some site containing platform",
"|ipsum.com| Some site containing discussion"
];
// returns the array containing multiple result
function urlReturn(pages, query) {
var result = []
pages.forEach(function(page) {
var match = (new RegExp('^\\|(.+?)\\|.*' + query + '.*', 'g')).exec(page);
if (match !== null) {
result.push(match[1]);
}
});
return (result);
}
console.log(urlReturn(pages, "platform"));
// ["stackoverflow.com", "lorem.com"]
console.log(urlReturn(pages, "discussion"));
// ["reddit.com", "ipsum.com"]
console.log(urlReturn(pages, "rating"));
// ["reddit.com"]

答案 3 :(得分:0)
您要求的功能的直接解决方案:
function urlReturn(pages, query) {
for(var i = 0; i < pages.length; i++) {
if (pages[i].indexOf(query) > 0) {
return pages[i].split("|")[1];
}
}
return '';
}
此函数搜索pages数组,直到找到包含query
参数的索引,然后使用字符串"|"
作为分隔符将索引处的值拆分为另一个数组并返回第二个数组此数组的索引[1]
,其中包含您要搜索的子字符串。如果不匹配,则返回空字符串。
检查它是否有效:
function urlReturn(pages, query) {
for(var i = 0; i < pages.length; i++) {
if (pages[i].indexOf(query) > 0) {
return pages[i].split("|")[1];
}
}
return '';
}
var pages = [
"|stackoverflow.com| The website serves as a platform for users to ask and answer questions." ,
"|reddit.com| A social news aggregation, web content rating, and discussion website"
];
console.log(urlReturn(pages, "platform"));
&#13;