Print javascript string object properties and methods

How to print properties and methods of a Javascript String object.

The following snippet does not print anything.

for (x in String) { document.write(x); } 
+4
source share
4 answers

The String properties are all non-enumerable, so your loop doesn't show them. You can see your own properties in ES5 using the Object.getOwnPropertyNames function:

 Object.getOwnPropertyNames(String); // ["length", "name", "arguments", "caller", "prototype", "fromCharCode"] 

You can verify that they are not enumerable using the Object.getOwnPropertyDescriptor function:

 Object.getOwnPropertyDescriptor(String, "fromCharCode"); // Object {value: function, writable: true, enumerable: false, configurable: true} 

If you want to see String instance methods, you need to look at String.prototype . Note that these properties are also not enumerable:

 Object.getOwnPropertyNames(String.prototype); // ["length", "constructor", "valueOf", "toString", "charAt"... 
+9
source

It must first be declared as Object (the keyword 'new' can be used)

 s1 = "2 + 2"; s2 = new String("2 + 2"); console.log(eval(s1)); console.log(eval(s2)); 

OR

 console.log(eval(s2.valueOf())); 
+2
source

try using the console in developer tools in Chrome or Firebug in Firefox.

and try this

  for (x in new String()) { console.log(x); } 
0
source

This should complete the task:

  var StringProp=Object.getOwnPropertyNames(String); document.write(StringProp); -->> ["length", "name", "arguments", "caller", "prototype", "fromCharCode"] 

But you may be more interested in:

  var StringProtProp=Object.getOwnPropertyNames(String.prototype); document.write(StringProtProp); -->> ["length", "constructor", "valueOf", "toString", "charAt", "charCodeAt", "concat", "indexOf", "lastIndexOf", "localeCompare", "match", "replace", "search", "slice", "split", "substring", "substr", "toLowerCase", "toLocaleLowerCase", "toUpperCase", "toLocaleUpperCase", "trim", "trimLeft", "trimRight", "link", "anchor", "fontcolor", "fontsize", "big", "blink", "bold", "fixed", "italics", "small", "strike", "sub", "sup"] 
0
source

All Articles