1

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.

2
  • 2
    What is slice(0, "") supposed to do? Btw [...string].length Commented Apr 28, 2019 at 19:45
  • @JonasWilms i thought it would give the end of the given string, but clearly i was wrong. Commented Apr 28, 2019 at 21:11

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.