2017-03-05 38 views
-1

實現,如果給定的字符串指定的通配符模式匹配返回True的函數,否則返回False。實現,如果給定的字符串指定的通配符模式匹配返回True的函數,否則返回False

允許使用內置split(),indexOf(),startsWith()endsWith()

這是非常相似的最後一個我沒有,但我似乎仍不能得到它的竅門。這裏是我到目前爲止

function matches(text, pattern) { 
 
    var x = pattern.split("*"); 
 
    var y = (text.indexOf(x[0]) !== -1); 
 
    for (i = 0; i< x.length; i++){ 
 
     if (y) { 
 
      y = (text.indexOf(x[i]) !== -1); 
 
     } 
 
    } 
 
    return y; 
 
} 
 

 
console.log(matches("lord of the rings", "lord*rings")); // Expected: True 
 
console.log(matches("lord of the rings", "Lord*rings")); // Expected: False 
 
console.log(matches("lord of the rings", "l*o*t*r")); // Expected: False 
 
console.log(matches("lord of the rings", "l*o*t*r*s")); // Expected: True 
 
console.log(matches("lord of the rings", "lord*")); // Expected: True 
 
console.log(matches("lord of the rings", "*rings")); // Expected: True 
 
console.log(matches("lord of the rings", "*the*")); // Expected: True 
 
console.log(matches("lord of the rings", "*")); // Expected: True 
 
console.log(matches("lord of the rings", "*z*")); // Expected: False

我所試圖做的是孤立的單詞,然後檢查他們中的每一個,如果所有的人都存在,那麼我回到true或者至少其中一個不是我返回false。但是出了點問題,我不太明白。

將不勝感激的解決方案,或者反饋給我的代碼,請保持它相當簡單。 謝謝!

+2

*「但不順心的事」 *是太過模糊是有用的。我會注意到你當前的代碼沒有做任何事情來檢查單個部分是否在通配符字符串指定的**順序**中。 –

+1

讓我說我們不是在這裏爲你做你的功課;) –

+0

Lelio這是什麼意思?我不知道你是否可以在我的個人資料中看到它,但我只是爲了好玩而編寫代碼,只是因爲我被困住了,並且現在正在撞牆撞了我一會兒。這不是因爲我有一個編碼類,這是我的作業。 – Lezhka

回答

0
function matches(text, pattern) { 
    while (text.length) { 
     if (text[0] !== pattern[0] && pattern[0] !== '*') 
      return false; 

     text = text.slice(1); 

     var wordAfterWildcard = pattern.split('*')[1]; 

     if (pattern[0] !== '*' || wordAfterWildcard && text.startsWith(wordAfterWildcard)) 
      pattern = pattern.slice(1); 
    } 
    return !(pattern && pattern.replace('*', '')); 
} 

//我做了你的功課,因爲我是個瘋子。不是因爲你。 //享受...

+0

Heeey對不起,看看我給Lelio的回答,我簡直就是輸入了。 – Lezhka

+0

好的,我很抱歉:) –

相關問題