2017-04-13 33 views
0

任何幫助將不勝感激:我只是不能繼續前我弄清楚我做錯了什麼..搜索文本的名稱(javascript)

我正在尋找一個文本名稱與一個for循環,然後試圖將這些字母推入數組。出於某種原因,這不是推動,我不知道我在做什麼錯誤..仍然是一個新手.. thx的幫助!

var text = "Code it out bro, it will just get Zane Zane Zane better 
from here, especially after your familiar with the various 
frameworks..yeah man..."; 
var hits = [ ]; 
var nameZane = "Zane"; 
for (i=0; i < text.length; i++) 
if (i === "Z"){ 
    for (j=i; j < nameZane.length + i; j++){ 
    hits.push(text[j])} 
} 

if (hits.length === 0){ 
    console.log("Couldn't find " + nameZane)} 
else{ 
    console.log(hits)} 
+1

何必太多這樣做。只要使用正則表達式這個 –

+0

將'i ===「Z」'永遠是_true_? – Satpal

+1

它應該是'text [i] ===「Z」' – gurvinder372

回答

0

是不是i其一個text[i]利用這個條件,如果像這樣if (text[i] === "Z") {

var text = "Code it out bro, it will just get Zane Zane Zane better from here, especially after your familiar with the variousframeworks..yeah man..."; 
 
var hits = []; 
 
var nameZane = "Zane"; 
 
for (i = 0; i < text.length; i++) 
 
    if (text[i] === "Z") { 
 
    for (j = i; j < nameZane.length + i; j++) { 
 
     hits.push(text[j]) 
 
    } 
 
    } 
 

 
if (hits.length == 0) { 
 
    console.log("What the f*** man?") 
 
} else { 
 
    console.log(hits) 
 
}

+0

只是一個小的優化。在'if'裏面'for'後,你可以做'i + = nameZane.length'。這將刪除不需要的迭代 – Rajesh

0

編輯代碼:
if (i === "Z")

if (text.charAt(i) == 'Z') 

hits.push(text[j]) 

hits.push(text.charAt(j)); 
0
var re = /Zane/g, 
str = "Code it out bro, it will just get Zane Zane Zane better from here, especially after your familiar with the various frameworks..yeah man..."; 
while ((match = re.exec(str)) != null) { 
    console.log("match found at " + match.index); 
}