I am trying to convert java code to javascript (js), and I'm quite frustrated by how js is missing many string methods. I'm aware of js string libraries and that you can do someString.length to get a string's length. But I was pleasantly surprised to see in the top answer to this topic: How to check if a string "StartsWith" another string? That the startsWith method can be defined in my own js code file like so:
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
So I tried to do something similar for the length method:
if (typeof String.prototype.length != 'function') {
String.prototype.length = function (){
return this.length;
};
}
var str = "a string";
alert(str.length());
But it doesn't work, I get the following error in chrome when I try to call: Uncaught TypeError: Property 'length' of object is not a function
Does anyone know why I can't create a length() function similarly to how it can be done for the startsWith(str) method explained above? Thanks, Keith