Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 951
James N Avatar asked Feb 18 '17 00:02

James N


People also ask

Can we find string length without using a loop or strlen ()?

Program to find the length of a string without using the strlen() function is discussed here. Length of a string can be found by scanning the string, character by character until an empty space '/0' is encountered.


Video Answer


2 Answers

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

like image 179
nnnnnn Avatar answered Sep 30 '22 14:09

nnnnnn


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

like image 25
Andrew Willems Avatar answered Sep 30 '22 14:09

Andrew Willems