简体   繁体   中英

A Function that Detects whether the first half of a string matches the second half - Homework Warning JS

I have this homework question and I cant figure out a good way of checking. I have went down the path of indexOf and string.repeat(), but just not getting what the question is looking for. I could do a reg ex, but since this is basic javascript I would like know how to do it without going there.

Question: Write a function named repeats that returns true if the first half of the string equals the last half, and false if not

Example:

If you pass it "haha" then it should return true because "ha" (the first half) equals "ha" (the second half) If you pass it "yay" then it should return false because it's odd If you pass it "heehaw" then it should return false because "hee" doesn't equal "haw" */

This is what I have so far after many attempts at looping and methods:

var stringEq = "haha";
var stringNoEq = "heehaw";

function stringEqual(string) {

    if (string.length % 2 !== 0) {
        return false;
      }
      else{
        string.length /2 
      }

    }

    stringEqual(stringEq)

Any help appreciated.

function stringEqual(myString) {
    if (myString.length % 2 != 0) {
        return false;
    }
    var firstHalf = myString.substr(0, myString.length/2);
    var secondHalf = myString.substr(myString.length/2);

    return firstHalf == secondHalf;
}
function halfStringAreEqual(string str){ if (str.length % 2 != 0) return false; var half = str.length / 2; return str.substr(0, half) == str.substr(half, str.length - half); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM