的OP的例子是Codecademy網站,所以如果有人正在尋找相關的專門的Javascript答案單詞邊界:6/7課程這是我想出了什麼:
/*jshint multistr:true */
var text = "How are you \
doing Sabe? What are you \
up to Sabe? Can I watch \
Sabe?";
var myName = "Sabe";
var hits = [];
for (var i = 0; i < text.length; i++) {
if (text[i] === 'D') {
for (var j = i; j < (i + myName.length); j++) {
hits.push(text[j]);
}
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
然後我決定像OP一樣去做額外的挑戰,那就是創建一個需要精確匹配的字符串。 codecademy JavaScript課程是爲完整的新手所以他們尋找的答案是使用for
循環和廣泛的if
/else
陳述來給我們實踐。
從一個學習曲線點擴展版本:
/*jshint multistr:true */
var text = "The video provides a powerful way to help you prove \
your point. When you click Online video, you can paste in the \
embed code for the video you want to add. You can also type a \
keyword to search online for the video that best fits your document.";
var theWord = "video";
var hits = [];
for (var i = 0; i < text.length; i++) {
if (theWord === text.substr(i,theWord.length)) {
hits.push(i);
i += theWord.length-1;
}
}
if (hits.length) {
for (i = 0; i < hits.length; i++) {
console.log(hits[i],text.substr(hits[i],theWord.length));
}
} else {
console.log("No matches found.");
}
再有就是通過@Sanda提到match()
這是好事,知道現實生活中的實例:
/*jshint multistr:true */
var text = "The video provides a powerful way to help you prove \
your point. When you click Online video, you can paste in the \
embed code for the video you want to add. You can also type a \
keyword to search online for the video that best fits your document.";
var hits = text.match(/video/g);
if (hits.length === 0) {
console.log("No matches found.");
} else {
console.log(hits);
}
我希望這有助於codecademy民間!
爲什麼不能像@BjörnRoberg建議的那樣使用正則表達式?這只是爲了... – philipp