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);
}
我希望这对 codecademy 的人们有所帮助!