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);   
}
1

4 Answers 4

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"...
Sign up to request clarification or add additional context in comments.

Comments

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()));

Comments

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);   
    }

1 Comment

minil wants the methods and properties of the String object, not the ones of a string object.
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"]

1 Comment

document.write? seriously?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.