3

I am working on a practice problem:

Return the length of a string without using javascript's native string.length method.

The only ways I could think of would be substring or slice, but I'm stumped.

4
  • 2
    What's your actual question now? Commented Feb 18, 2017 at 0:57
  • Possible duplicate of How do you get a string to a character array in JavaScript? Commented Feb 18, 2017 at 1:00
  • @KyleMuir not a duplicate. like nnnnnn said, i cant use any native length methods. that includes arrays Commented Feb 18, 2017 at 3:10
  • This question is similar to: How to check string length with JavaScript. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 27 at 19:29

13 Answers 13

16

You can loop over the string, testing to see whether there is a non-undefined value at each index (as soon as you get an undefined value you've run past the end of the string):

function strLength(s) {
  var length = 0;
  while (s[length] !== undefined)
    length++;
  return length;
}

console.log(strLength("Hello")); // 5
console.log(strLength("")); // 0

(I'm assuming that if you're not allowed to use the native string .length property that you probably shouldn't use the array .length property either with str.split("").length...)

Sign up to request clarification or add additional context in comments.

1 Comment

i actually tried a variation of that using a for-loop and it failed the tests due to both of your correct assumptions. which is why i was originally looking for how to do this in either slice or substring. this is what it should have been
4

Given that this is a practice problem, I suspect the OP may not want ES6/ES2015, but, just in case that's an option, and/or for whoever else is looking at this, here's a concise modern approach:

const str = "Hello world!";

console.log([...str].reduce(a => a+1, 0));

(When I posted this, no other answer had proposed this solution. However, I had missed the fact that @MarkoGrešak had essentially proposed this exact solution in a comment to another question.)

1 Comment

Even with str.split("") and a traditional non-arrow function reducer this would still be pretty concise.
1

You can use spread element, Array.prototype.keys() iterator, Array.prototype.pop()

var str = "abc";
var len = [...[0,...str].keys()].pop();
console.log(len, str.length);

Comments

1

The briefest have been able to achieve so far using Object.keys(), Array.prototype.pop() and checking for empty string. Approach could probably be improved further.

var len = str === "" ? 0 : +Object.keys(str).pop()+1;

@nnnnnnn utilizes the two methods at above far exceeding the initial attempt in brevity and addressing case of empty string.

var len = +Object.keys(str+' ').pop();

5 Comments

You could save a character with == instead of ===. You could save some pixels with ' instead of ".
@nnnnnn Also removing eight space characters from line. Still have sense the line can be further reduced
var len = (+Object.keys(str).pop()+1)||0
@nnnnnn There is that OR conjured at previous post.
var len = +Object.keys(str+' ').pop() - You were really onto something with the popping keys concept.
0

One way would be iterating through a split string like so:

var count = 0;
Array.from("string here".split("")).forEach(function(){count++});

Tip from Marko below in the comments to use the reduce function to shorten it to:

var count = Array.from("string here".split("")).reduce(function(count){return count+1}, 0);

5 Comments

If you're going to do it like that, at least use .reduce(function(count) { return count + 1}, 0).
That's a good thought, have been meaning to use the reduce function more recently.
@MarkoGrešak, I had checked the other answers before I posted mine, but I hadn't seen your comment which proposed the same solution I did. Just wanting to give credit where it's due.
Thank you @AndrewWillems! @andrew196 the idea of reduce is not to only shorten the code, but also to avoid having an external state, but keep everything local to the reduce callback function. This way you don't have to worry about resetting the state before computing the length multiple times.
Thank you, @MarkoGrešak. Good to know
0

You could use array.length so you answer the question not using the native string.length.

var Str = "Hello world!";
const CountAr = Str.split("").length;
console.log(CountAr);
/*12*/

Comments

0
function stringLength(str) {
  var count = 0;
  var index = 0;

  while(string[index] !== undefined){
    count += 1;
    index += 1;
  }
  return count;
}

1 Comment

While code only answers may answer the question, you should explain them to those who may not understand.
0

I think this will work. If you start with '', it won't go into the while loop, and you'll just return 0.

function getStringLength(string) {
  var idx = 0;
  while (string[idx] !== undefined) {
    idx += 1;
  }
  return idx;
}

Comments

0

This will work.

function  length(str) {
    str = str.split(''); 
    var length = 0;
    str.forEach(function(element) { 
    length++;  
    });
    return length;    
}

length('hello'); // output 5

Comments

0

Yet another way to do it

function getStringLength(str){
  var count = 0;
  for(var letter in str){
    count += 1;
  }
  return count;
}

console.log(getStringLength('Mississippi')) // 11
console.log(getStringLength('')) // 0 

Comments

0

The for in loop is the way to go I think. You can use slice or substring but for in loops can count strings easily too.

function getStringLength(string) {
      var length = 0;
      for (var i in string){
        length++;
      }
      return length;
      }

Comments

0

This is the solution I came up with
I have used a while loop for getting the length of the input
Sharing Two approaches with a while loop

Approach no 1

    function getLength(input) {
        if(!input){
          return 'please provide input'
        }
        let i = 0;
        while (true) {
            if (input[i]) {
                i += 1
            }else{
                break
            }
        }
        return i
    }
    
console.log(getLength([1, 5, 3, 7, 8])) // 5
console.log(getLength("Hare Krishna")) // 12

Output
5 (for array)
12 (for string)

Approach no 2

function getLength(input){
  let i = 0;
  while(input[i] !== undefined){
    i++;
  }
  return i
}

console.log(getLength([1,2,3,48,8,9])) // 6

Output
6 (for array)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0
function getStringLength(string) {
// Do NOT use any native 'length' methods.
// You might consider using 'substring' or 'slice' as alternatives.
 
  let i = 0;
  while (Number(string.slice(i, i+1)) !== 0) {
    i++;
 } return i;
}

var output = getStringLength('hello');
console.log(output); // --> 5

1 Comment

this is a code only answer. Consider adding a helpful description.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.