Here, a string could be a variable with a string value or a direct string written in quotes (” “).
Explanation: String str1 has a value of “Hello Geeks” and has a length of 11. We can directly get the 11 by counting it on our own. And remember length method counts the length when it will encounter any character even if it is an encounter with space, it will count it.
Explanation: String str2 has a value of ” Hello Geeks ” and has a length of 15 calculated by the length method. But the actual length of string str2 is 11 only, so because the length method calculates the length of character which is enclosed in quotes no matter what it is.
But we need actual length so how we can achieve it? We can achieve it by defining the prototype for a String object. In the definition, we will define the implementation of this operation.
So let’s see the implementation of the new truelength method define by using the prototype.
Variable “geeks” is a String object and that object contains the length method which gives the space counted length so we will modify the length method and of name truelength by defining the prototype of the string object. trim() method of String object will return the string by removing the white spaces from the start and end of the string. We will get the trimmed string then we can calculate the length of the given string and that length of the string will be the actual string length without start and end spaces.
Please Login to comment...