Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting middle of string - JavaScript

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");
like image 265
MadCatm2 Avatar asked Oct 28 '25 19:10

MadCatm2


2 Answers

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"));
like image 174
Alexey Soshin Avatar answered Oct 30 '25 08:10

Alexey Soshin


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);
}
like image 29
Karolina Avatar answered Oct 30 '25 10:10

Karolina