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.");
}
次にmatch()
、実際のインスタンスについて知っておくとよい @Sanda による言及があります。
/*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);
}
これがコードアカデミーの人々に役立つことを願っています!