2016-11-14 94 views
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"] 

當用戶輸入urlReturn(pages,"platform"),函數應該輸出stackoverflow.com

我都試過,但無濟於事,幫助將不勝感激!

+0

爲什麼 「stackoverflow.com」,而不是 「reddit.com」? –

+0

由於串「平臺」出現在「stackoverflow.com」舉行的字符串中,而不是「reddit.com」舉行的地方 – Johny

回答

0
var urlReturn = (pages, text) => pages.filter(page => page.indexOf(text) > -1).map(page => /\|([^|]*)\|/.exec(page)[1]) 

我建議你在MDN中查找這些東西。關於正則表達式和集合有幾篇很好的文章/文檔。

0
for (idx in pages) { 
    if (pages[idx].indexOf('platform') != -1) { 
     console.log(pages[idx].substr(1, pages[idx].indexOf('|', 1) - 1)) 
    } 
} 
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"]

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 ''; 
} 

該函數查找頁面數組,直到找到索引包含爲止然後使用字符串"|"作爲分隔符將索引處的值拆分爲另一個數組並返回此數組的第二個索引[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"));