5

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.

James N
  • 523
  • 1
  • 8
  • 30
  • 1
    What's your actual question now? – Felix Kling Feb 18 '17 at 00:57
  • Possible duplicate of [How do you get a string to a character array in JavaScript?](http://stackoverflow.com/questions/4547609/how-do-you-get-a-string-to-a-character-array-in-javascript) – Kyle Muir Feb 18 '17 at 01:00
  • @KyleMuir not a duplicate. like nnnnnn said, i cant use any native length methods. that includes arrays – James N Feb 18 '17 at 03:10

13 Answers13

17

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...)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 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 – James N Feb 18 '17 at 03:14
5

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.)

Andrew Willems
  • 11,880
  • 10
  • 53
  • 70
  • Even with `str.split("")` and a traditional non-arrow function reducer this would still be pretty concise. – nnnnnn Feb 18 '17 at 01:12
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);
guest271314
  • 1
  • 15
  • 104
  • 177
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();
guest271314
  • 1
  • 15
  • 104
  • 177
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);
  • 1
    If you're going to do it like that, at least use `.reduce(function(count) { return count + 1}, 0)`. – Marko Gresak Feb 18 '17 at 01:03
  • That's a good thought, have been meaning to use the reduce function more recently. –  Feb 18 '17 at 01:05
  • @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. – Andrew Willems Feb 18 '17 at 01:10
  • 2
    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. – Marko Gresak Feb 18 '17 at 01:14
  • Thank you, @MarkoGrešak. Good to know –  Feb 18 '17 at 01:18
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*/
cpugourou
  • 775
  • 7
  • 11
0
function stringLength(str) {
  var count = 0;
  var index = 0;

  while(string[index] !== undefined){
    count += 1;
    index += 1;
  }
  return count;
}
  • 2
    While code only answers may answer the question, you should explain them to those who may not understand. – Enstage May 17 '17 at 01:39
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;
}
Daniel T
  • 23
  • 5
0

This will work.

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

length('hello'); // output 5

MANJEET
  • 1,733
  • 2
  • 12
  • 21
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 
I0_ol
  • 1,054
  • 1
  • 14
  • 28
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;
      }
Aaron Cloud
  • 315
  • 4
  • 15
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
    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](/help/how-to-answer). – Community Jan 17 '22 at 07:26
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
jesse
  • 1
  • 1