简体   繁体   中英

How to define a javascript string.length() function?

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

String instances are created with an immutable length property which isn't inherited from String.prototype. So you won't be able to create a length() method for Strings.

See http://ecma-international.org/ecma-262/5.1/#sec-15.5.5

String instances inherit properties from the String prototype object and their [[Class]] internal property value is "String". String instances also have a [[PrimitiveValue]] internal property, a length property, and a set of enumerable properties with array index names.

And see http://ecma-international.org/ecma-262/5.1/#sec-15.5.5.1

Once a String object is created, this property is unchanging. It has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

It's simple. Just implement the prototype of object.

// Defines the name what You want
String.prototype.size = function () {
   return this.length;
}

'abc'.size ();

If You want some nice implementations, go ahead:

// Defines the name what You want
String.prototype.untilChar = function (charEnding) {
   return charEnding && this.includes (charEnding) ? this.substr (0, this.indexOf (charEnding)).length : this.length;
}

'abcdefg'.untilChar ('d'); // Returns 3
'abcdefg'.untilChar ('z'); // Returns 7

If You can't get the correct solution, don't even try with runarounds! ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM