How to print the properties and methods of javascript String object.
Following snippet does not print anything.
for (x in String) {
document.write(x);
}
How to print the properties and methods of javascript String object.
Following snippet does not print anything.
for (x in String) {
document.write(x);
}
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"...
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()));
try using the console in developer tools in Chrome or Firebug in Firefox.
and try this
for (x in new String()) {
console.log(x);
}
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"]