4

How to print the properties and methods of javascript String object.

Following snippet does not print anything.

for (x in String) {
   document.write(x);   
}
minil
  • 6,895
  • 16
  • 48
  • 55
  • possible duplicate of [Is it possible to get the non-enumerable inherited property names of an object?](http://stackoverflow.com/questions/8024149/is-it-possible-to-get-the-non-enumerable-inherited-property-names-of-an-object) – Joseph Apr 10 '13 at 07:46

4 Answers4

9

The properties of String are all non-enumerable, which is why your loop does not show them. You can see the own properties in an ES5 environment with the Object.getOwnPropertyNames function:

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

You can verify that they are non-enumerable with 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 will need to look at String.prototype. Note that these properties are also non-enumerable:

Object.getOwnPropertyNames(String.prototype);
// ["length", "constructor", "valueOf", "toString", "charAt"...
James Allardice
  • 164,175
  • 21
  • 332
  • 312
2

First It must be declared as Object,(may be using 'new' keyword)

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

OR

console.log(eval(s2.valueOf()));
Nimesh Vagadiya
  • 602
  • 3
  • 8
  • 18
0

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

and try this

    for (x in new String()) {
       console.log(x);   
    }
Stuart Grant
  • 414
  • 3
  • 12
  • minil wants the methods and properties of the `String` object, not the ones of *a* string object. – MaxArt Apr 10 '13 at 07:44
0

This should do the job :

 var StringProp=Object.getOwnPropertyNames(String);

 document.write(StringProp); 

 -->>  ["length", "name", "arguments", "caller", "prototype", "fromCharCode"]

But you might be more interested by :

 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"]
GameAlchemist
  • 18,995
  • 7
  • 36
  • 59