的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