How to get length of string in javascript without using native length method

Solution 1:

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

Solution 2:

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

Solution 3:

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

Solution 4:

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