Shreeya Bhetwal
Shreeya Bhetwal

Reputation: 45

Creating string length function in JavaScript

Your task is to write a function called stringLength that accepts a string as a parameter and computes the length of that string; however, as you may have guessed, you are not allowed to use the length property of the string!

Instead, you'll need to make use of the string method called slice.

My program is not creating the right output. Please explain the error in my code.

function stringLength(string) {
let start =0;
let end= string.slice(0, "");
let result=0;
for(let i=start; i<=end; i++){
result++;
}
 return result;
}

My output is 1

Whereas the output should return the length of the given string.

Upvotes: 1

Views: 1557

Answers (3)

Guilherme Lemmi
Guilherme Lemmi

Reputation: 3487

You can use the method split with '' as parameter, which will return an array with all the letters of the string. Then, just iterate through this array using the method reduce, adding 1 to a counter for each letter, like below:

function stringLength(string) {
        return string.split('').reduce(function (length) {
            return length + 1;
        }, 0);
}

With ES6 syntax, it gets even shorter:

function stringLength(string) {
        return string.split('').reduce((length) => length + 1, 0);
}

Upvotes: 0

Fundhund
Fundhund

Reputation: 141

You could try this:

function stringLength(string) {

  let index = 0;

  while (string.slice(index) !== '') {
    index++;
  }

  return index;
}

string.slice(index) will return the substring from character at index index until the end of the string. If index exceeds the biggest index in the string, it returns an empty string. That's how you know you have to stop counting.

You could even do it without slice at all:

function stringLength(string) {

    let count = 0;

    for(let char of string) {
        count++;
    }

    return count;
}

Upvotes: 2

zeev gerstner
zeev gerstner

Reputation: 15

Slice can get one parameter for start index and it will slice till the end or two parameters for start index and end index. You can't put "" as a parameter Look here

Upvotes: 0

Related Questions