I am trying to write an algorithm for this in JavaScript but I am getting a str.length is not a function...
function extractMiddle(str) {
    var position;
    var length;
    if(str.length() % 2 == 1) {
        position = str.length() / 2;
        length = 1;
    } else {
        position = str.length() / 2 - 1;
        length = 2;
    }
    result = str.substring(position, position + length)
}
extractMiddle("handbananna");
Because string length is not a function, it's a property.
 function extractMiddle(str) {
        var position;
        var length;
        if(str.length % 2 == 1) {
            position = str.length / 2;
            length = 1;
        } else {
            position = str.length / 2 - 1;
            length = 2;
        }
        return str.substring(position, position + length)
    }
    console.log(extractMiddle("handbananna"));
Here is an another way to do this:
function extractMiddle(str) {
  return str.substr(Math.ceil(str.length / 2 - 1), str.length % 2 === 0 ? 2 : 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With