2

このコードを微調整して、名前と完全に一致するものだけを見つけるのに役立つ組み込みの JavaScript 文字列メソッドはありますか?

これが私のコードです。

/*jshint multistr:true */

var text = "Sid quick brown fox jumps over the lazy dog ";
var myName = "Sid";
var hits = [];

for (var i=0; i< text.length; i++){
    if(text[i] === 'S'){
        for(var j=i; j < i + myName.length; j++){
            hits.push(text[j]);
        }
    }else{
        console.log("Your name wasn't found!")
    }

}
console.log(hits);
4

10 に答える 10

5

したがって、 function を使用した別の解決策がありますmatch()が、より簡単です。

/*jshint multistr:true */
var text = "Hey, how are you doing Sanda? My name is Emily.\
Nice to meet you Sada. Where does your name come from, Sana?\
is Sanda a slavic name?";
/*var myName = "Sanda";
hits = [];

for(var i=0; i < text.length; i++ ){
    if (text[i] === myName[0]) 
        for (var j=i; j< i + myName.length && j < text.length; j++ ) 
            hits.push(text[j]);
}

if ( hits.length === 0 ) "Your name wasn't found!";
else console.log(hits);*/

var hits = text.match(/Sanda/g);

if ( hits.length === 0 ) "Your name wasn't found!";
else console.log(hits);

構文はvar <someVar> = <textToBeSearched>.match(/pattern/modifiers). 私の修飾子gはグローバル用です(パターン全体を検索します)。

詳細はこちら: http://www.w3schools.com/jsref/jsref_match.asp http://www.w3schools.com/js/js_regexp.asp

乾杯!

于 2014-05-24T06:43:12.663 に答える
2

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);
}

 

これがコードアカデミーの人々に役立つことを願っています!

于 2015-09-27T10:12:49.590 に答える
1

Code Academy の Javascript 基礎コースでも、この演習に遭遇しました。

私の解決策は以下です。かなり基本的ですが、仕事をしました。

var text = "There is a real risk of the British economy being harmed Olly which has the potential to create an environment in which businesses could go under and Olly jobs could be lost. The economic Oggle uncertainty was tangible yesterday as global financial markets lost Olly up to $2 Trillion USD value and the pound was at it’s lowest value for 30 years before recovering somewhat."

var myName = "Olly"
var hits = []

for (var i = 0; i < text.length; i++) {
    if (text[i] === "O" && text[i +1] === "l" && text [i +2] === "l" &&     text[i + 3] === "y") {
        for(var j = i; j < (myName.length + i); j++) {
            hits.push(text[j]);
        }
    }
}

if (hits.length === 0) {
    console.log("Your name wasn't found!");   
} else {
    console.log(hits);
}
于 2016-08-13T18:36:35.417 に答える
1
var text = "Blah blah blah blah blah blah Hafeez \
blah blah blah Hafeez blah blah Hafeez blah blah \
blah blah blah blah blah Huzaif, Hazere";

var myName = "Hafeez";
var hits = [];

for (var i =0; i < text.length ; i++)
{
   if(text[i] === 'H')
   {
       for(var j = i; j < (myName.length + i); j++) 
       {
           if (text.substring(i, (myName.length + i)) === myName)
           {
                hits.push(text[j])
           }
        }

    }
}

if(hits === 0)
{
    console.log("Your name was'nt found");

}
else
{
    console.log(hits);
    console.log(hits.length);
}
于 2014-11-13T11:48:12.777 に答える
0

これが他のいくつかの回答とそれほど異なるかどうかはわかりませんが、これはRegExを使用せずに配列変数に問題の文字列のすべての出現を入力する方法です。同様に、追加された substring() の String メソッドのみを使用してそれを実行したため、これが別の可能な答えになります。お役に立てれば:

var text = "blah bhlekm kdnclwi Christian blah blah, lots of blah in this text, blahChristian got one more Christian, and that's it.";
var myName="Christian";
var hits = [];
for (i=0; i<text.length; i++){
    if (text.substring(i, i+ myName.length) === myName){
            hits.push(text.substring(i, i+myName.length));
        }
    }

    if (hits.length == 0){
        console.log("Your name wasn't found!");
    }else{
        console.log("your name showed up " + hits.length + " times.");
    }
于 2013-10-29T12:52:17.373 に答える
0

とにかく、より良いコードがいくつかあります

check(0);

function check(start){
if ( text.subStr(start).indexOf(myName) >= 0 ){
hits++;
    check(text.subStr(start).indexOf(myName));
}
}
if (hits < 1 ){
    console.log("Your name wasn't found!")
}
console.log(hits);

動作するかどうかはまだ確認していませんが、一般的な考え方です

はい、答えは「組み込みのJavascript文字列メソッドがあり、このコードを微調整して、名前と完全に一致するものだけが見つかるようにするのに役立ちます。」

于 2013-08-26T00:23:17.880 に答える
0

substrを使用したソリューションは次のとおりです。

/*jshint multistr:true */

var text = "Lampe hinab la Samir licht schen er te recht. \
        Furchtete verodeten wo te Song flanierte \
        grundlich er Samir he. Bekam einem blank \
        da so schlo mu so.",
    myName = "Samir",
    hits = [];

for (var i = 0; i < text.length; i++) {
    if (text[i] === myName[0]) {
       var substr = text.substr(i, myName.length);
        if (substr === myName) {
           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);
};
于 2016-02-24T12:01:50.320 に答える
0

正規表現を使用してみることができます:

var text = "Sid quick brown fox jumps over the lazy dog ";
var myName = "Sid";

var re = new RegExp(myName);

re.exec(text);
// => ["Sid"]

または、どうしても文字列メソッドが必要な場合:

myName.match(re);
于 2013-09-05T15:06:57.420 に答える
0

これは、substring() 関数と search() 関数を使用した私自身のソリューションです。これは、テキストをチェックインして探している単語を見つける組み込みの JavaScript 文字列メソッドです。成功すると、その単語が存在するテキストの位置が返されます。失敗した場合は -1 の値が返されます。それを行う別の方法です。

/*jshint multistr:true */
var text = "hey wassup mike? \
wanna play football with mike, maria and antonis?!??!??!?!";
var myName = "mike";
var hits = [];
var pos = text.search(myName);

while(pos !== -1) {
     for (var j = 0; j < myName.length; j++) {
            hits.push(myName[j]);
        }
    text = text.substring(pos+myName.length,text.length);
    pos = text.search(myName);
}

if(hits === "")
{
    console.log("Your name wasn't found!");
}
else 
{
    for (var h = 0; h < hits.length; h++) {
        console.log(hits[h]);
    }
}
于 2015-06-28T15:55:34.267 に答える