Extracting middle of string - JavaScript

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

// the most amazing

const getMiddle = s => s.substr(s.length - 1 >>> 1, (~s.length & 1) + 1);

// should return "dd"

console.log(getMiddle('middle'))

// >>> is an unsigned right shift bitwise operator. It's equivalent to division by 2, with truncation, as long as the length of the string does not exceed the size of an integer in Javascript.

// About the ~ operator, let's rather start with the expression n & 1. This will tell you whether an integer n is odd (it's similar to a logical and, but comparing all of the bits of two numbers). The expression returns 1 if an integer is odd. It returns 0 if an integer is even.

// If n & 1 is even, the expression returns 0.

// If n & 1 is odd, the expression returns 1.

// ~n & 1 inverts those two results, providing 0 if the length of the string is odd, and 1 if the length of the sting is even. The ~ operator inverts all of the bits in an integer, so 0 would become -1, 1 would become -2, and so on (the leading bit is always the sign).

// Then you add one, and you get 0+1 (1) characters if the length of the string is odd, or 1+1 (2) characters if the length of the string is even.

@author by jacobb

the link of the source is: https://codepen.io/jacobwarduk/pen/yJpAmK


That seemed to fix it!

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)
    console.log(result);

}

https://jsfiddle.net/sd4z711y/