Search completed in 2.75 seconds.
401 results for "toString":
Your results are loading. Please wait...
Object.prototype.toString() - JavaScript
the tostring() method returns a string representing the object.
... syntax obj.tostring() return value a string representing the object.
... description every object has a tostring() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected.
...And 14 more matches
Function.prototype.toString() - JavaScript
the tostring() method returns a string representing the source code of the function.
... syntax function.tostring() return value a string representing the source code of the function.
... description the function object overrides the tostring method inherited from object; it does not inherit object.prototype.tostring.
...And 6 more matches
Number.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified number object.
... syntax numobj.tostring([radix]) parameters radix optional.
... exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown.
...And 6 more matches
JS_ValueToString
syntax jsstring * js_valuetostring(jscontext *cx, jsval v); name type description cx jscontext * the context in which to perform the conversion.
... description js_valuetostring converts a specified javascript value, v, to a string.
... it implements the tostring operator specified in ecma 262-3 §9.8.
...And 5 more matches
Array.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified array and its elements.
... syntax arr.tostring() return value a string representing the elements of the array.
... description the array object overrides the tostring method of object.
...And 5 more matches
BigInt.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified bigint object.
... syntax bigintobj.tostring([radix]) parameters radixoptional optional.
... exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown.
...And 5 more matches
Date.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified date object.
... syntax dateobj.tostring() return value a string representing the given date.
... description date instances inherit their tostring() method from date.prototype, not object.prototype.
...And 5 more matches
TypedArray.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified array and its elements.
... this method has the same algorithm as array.prototype.tostring().
... syntax typedarray.tostring() return value a string representing the elements of the typed array.
...And 5 more matches
Boolean.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified boolean object.
... syntax bool.tostring() return value a string representing the specified boolean object.
... description the boolean object overrides the tostring method of the object object; it does not inherit object.prototype.tostring().
...And 4 more matches
Symbol.toStringTag - JavaScript
the symbol.tostringtag well-known symbol is a string valued property that is used in the creation of the default string description of an object.
... it is accessed internally by the object.prototype.tostring() method.
... property attributes of symbol.tostringtag writable no enumerable no configurable no examples default tags object.prototype.tostring.call('foo'); // "[object string]" object.prototype.tostring.call([1, 2]); // "[object array]" object.prototype.tostring.call(3); // "[object number]" object.prototype.tostring.call(true); // "[object boolean]" object.prototype.tostring.call(undefined); // "[object undefined]" object.prototype.tostring.call(null); // "[obj...
...And 3 more matches
JS::ToString
syntax #include "js/conversions.h" // as of spidermonkey 38; previously in jsapi.h jsstring* js::tostring(jscontext *cx, js::handlevalue v) name type description cx jscontext * the context in which to perform the conversion.
... description js::tostring returns a string representation of a javascript value.
... if v.isstring() is true, it calls v.tostring().
...And 2 more matches
Range.toString() - Web APIs
WebAPIRangetoString
the range.tostring() method is a stringifier returning the text of the range.
... alerting the contents of a range makes an implicit tostring() call, so comparing range and text through an alert dialog is ineffective.
... syntax text = range.tostring(); example html <p>this example logs <b>everything</b> between the bold <b>words</b>.
...And 2 more matches
Selection.toString() - Web APIs
the selection.tostring() method returns a string currently being represented by the selection object, i.e.
... syntax sel.tostring() return value a string representing the selection.
... in javascript, this method is called automatically when a function the selection object is passed to requires a string: alert(window.getselection()) // what is called alert(window.getselection().tostring()) // what is actually being effectively called.
...And 2 more matches
Error.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified error object.
... syntax e.tostring() return value a string representing the specified error object.
... description the error object overrides the object.prototype.tostring() method inherited by all objects.
...And 2 more matches
Intl.Locale.prototype.toString() - JavaScript
the intl.locale.prototype.tostring() returns the locale's full locale identifier string.
... syntax locale.tostring() return value the locale's unicode locale identifier string.
...calling the tostring method on a locale object will return the identifier string for that particular locale.
...And 2 more matches
RegExp.prototype.toString() - JavaScript
the tostring() method returns a string representing the regular expression.
... syntax regexobj.tostring(); return value a string representing the given object.
... description the regexp object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring().
...And 2 more matches
String.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified object.
... syntax str.tostring() return value a string representing the calling object.
... description the string object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring().
...And 2 more matches
Symbol.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified symbol object.
... syntax symbol().tostring() return value a string representing the specified symbol object.
... description the symbol object overrides the tostring method of the object object; it does not inherit object.prototype.tostring().
...And 2 more matches
nsAutoString
class declaration nstautostring_chart subclass of nststring_chart that adds support for stack-based string allocation.
... names: nsautostring for wide characters nscautostring for narrow characters method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat...
... methods constructors void nsautostring() - source constructors void nsautostring(prunichar) - source parameters prunichar c void nsautostring(const prunichar*, pruint32) - source parameters prunichar* data pruint32 length void nsautostring(const nsautostring&) - source parameters nsautostring& str void nsautostring(const nsastring_internal&) - source parameters nsastring_internal& str void nsautostring(cons...
...t nssubstringtuple&) - source parameters nssubstringtuple& tuple operator= nsautostring& operator=(const nsautostring&) - source parameters nsautostring& str nsstring& operator=(const nsstring&) - source parameters nsstring& str nsastring_internal& operator=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& operator=(const nssubstringtuple&) - source parameters nssubstringtuple& tuple get prunichar* get() const - source returns the null-terminated string find print32 find(const nscstring&, prbool, print32, print32) const - source search for the...
nsCAutoString
class declaration nstautostring_chart subclass of nststring_chart that adds support for stack-based string allocation.
... names: nsautostring for wide characters nscautostring for narrow characters method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint ap...
... methods constructors void nscautostring() - source constructors void nscautostring(char) - source parameters char c void nscautostring(const char*, pruint32) - source parameters char* data pruint32 length void nscautostring(const nscautostring&) - source parameters nscautostring& str void nscautostring(const nsacstring_internal&) - source parameters nsacstring_internal& str vo...
...id nscautostring(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple operator= nscautostring& operator=(const nscautostring&) - source parameters nscautostring& str nscstring& operator=(const nscstring&) - source parameters nscstring& str nsacstring_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstring_internal& str nsacstring_internal& operator=(const nscsubstringtuple&) - source parameters nscsubstringtuple& tuple get char* get() const - source returns the null-terminated string find print32 find(const ...
XMLSerializer.serializeToString() - Web APIs
the xmlserializer method serializetostring() constructs a string representing the specified dom tree in xml form.
... syntax xmlstring = anxmlserializer.serializetostring(rootnode); parameters rootnode the node to use as the root of the dom tree or subtree for which to construct an xml representation.
... notes on the resulting xml there are some things worth noting about the xml output by serializetostring(): for xml serializations, element and attr nodes are always serialized with their namespaceuri intact.
... specifications specification status comment dom parsing and serializationthe definition of 'serializetostring()' in that specification.
JS_VersionToString
syntax const char * js_versiontostring(jsversion version); name type description version jsversion version value to convert.
... description js_versiontostring attempts to convert the version to a const char * string representation.
... js_versiontostring may return any of the following values: enumeration string jsversion_1_0 "1.0" obsolete since jsapi 24 jsversion_1_1 "1.1" obsolete since jsapi 24 jsversion_1_2 "1.2" obsolete since jsapi 24 jsversion_1_3 "1.3" obsolete since jsapi 24 jsversion_1_4 "1.4" obsolete since jsapi 24 jsversion_ecma_3 "ecmav3" jsversion_1_5 "1.5" obsolete since jsapi 24 jsversion_1_6 "1.6" jsversion_1_7 "1.7" jsversion_1_8 "1.8" jsversion_ecma_5 "ecmav5" jsversion_default "default" other null see also mxr id search for js_stringtoversion jsversion js_getversion js_setversionforcompartment js_stringtoversion bug 824312 ...
URL.toString() - Web APIs
WebAPIURLtoString
the url.tostring() stringifier method returns a usvstring containing the whole url.
... syntax const href = url.tostring() return value a usvstring.
... examples const url = new url("/docs/web/api/url/tostring"); url.tostring(); // should return the url as a string specifications specification status comment urlthe definition of 'stringifier' in that specification.
URLSearchParams.toString() - Web APIs
the tostring() method of the urlsearchparams interface returns a query string suitable for use in a url.
... syntax urlsearchparams.tostring() parameters none.
...params.append('foo', 4); console.log(params.tostring()); //prints 'foo=1&bar=2&foo=4' // note: params can also be directly created let url = new url('https://example.com?foo=1&bar=2'); let params = url.searchparams; // or even simpler let params = new urlsearchparams('foo=1&bar=2'); specifications specification status comment urlthe definition of 'tostring() (see "stringifier")' in that specification.
URLUtilsReadOnly.toString() - Web APIs
the urlutilsreadonly.tostring() stringifier method returns a domstring containing the whole url.
... syntax string = object.tostring(); examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.href var result = window.self.tostring(); // returns:'https://developer.mozilla.org/urlutilsreadonly.href' browser compatibility the compatibility table in this page is generated from structured data.
... desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internettostring experimentalchrome no support noedge no support nofirefox full support 3.5ie no support noopera no support nosafari no support nowebview android no support nochrome android no suppo...
toString - Archive of obsolete content
method of installversion object syntax string version = installversion.tostring ( initobj ); parameters the tostring method has the following parameter: initobj initobj is an installversion object whose init method has been called.
...to get the version number out of an installversion object in order to compare it with other versions, you can call tostring() and get back the version as a string in the format "maj.min.rev.bld." example var vi = new installversion(); vi.init("999.888.777.666"); //random string vistring = vi.tostring(); ...
HTMLHyperlinkElementUtils.toString() - Web APIs
the htmlhyperlinkelementutils.tostring() stringifier method returns a usvstring containing the whole url.
... syntax string = object.tostring(); examples // let's imagine an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils/tostring"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.tostring(); // returns: 'https://developer.mozilla.org/docs/htmlhyperlinkelementutils/tostring' specifications specification status comment html living standard living standard ...
Location: toString() - Web APIs
WebAPILocationtoString
the tostring() stringifier method of the location interface returns a usvstring containing the whole url.
... syntax string = object.tostring(); examples // let's imagine an <a id="myanchor" href="https://developer.mozilla.org/docs/location/tostring"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.tostring(); // returns: 'https://developer.mozilla.org/docs/location/tostring' specifications specification status comment html living standard living standard ...
Map.prototype[@@toStringTag] - JavaScript
the map[@@tostringtag] property has an initial value of "map".
... property attributes of map.prototype[@@tostringtag] writable no enumerable no configurable yes syntax map[symbol.tostringtag] examples using tostringtag object.prototype.tostring.call(new map()) // "[object map]" specifications specification ecmascript (ecma-262)the definition of 'map.prototype[@@tostringtag]' in that specification.
PR_NetAddrToString
syntax #include <prnetdb.h> prstatus pr_netaddrtostring( const prnetaddr *addr, char *string, pruint32 size); parameters the function has the following parameters: addr a pointer to the network address to be converted.
toString
this content is now available at nsisupportscstring.tostring().
toString
this content is now available at nsisupportschar.tostring().
toString
this content is now available at nsisupportsdouble.tostring().
toString
this content is now available at nsisupportsfloat.tostring().
toString
this content is now available at nsisupportsid.tostring().
toString
this content is now available at nsisupportsinterfacepointer.tostring().
toString
this content is now available at nsisupportsprbool.tostring().
toString
this content is now available at nsisupportsprint16.tostring().
toString
this content is now available at nsisupportsprint32.tostring().
toString
this content is now available at nsisupportsprint64.tostring().
toString
this content is now available at nsisupportsprtime.tostring().
toString
this content is now available at nsisupportspruint16.tostring().
toString
this content is now available at nsisupportspruint32.tostring().
toString
this content is now available at nsisupportspruint64.tostring().
toString
this content is now available at nsisupportspruint8.tostring().
toString
this content is now available at nsisupportsstring.tostring().
toString
documentation is now located at nsisupportsvoid.tostring().
Mozilla internal string guide
every 16-bit class has an equivalent 8-bit class: naming convention for wide and narrow string classes wide narrow nsastring nsacstring nsstring nscstring nsautostring nsautocstring etc...
...ounted, copy-on-write, buffers (the default) adopted buffers (a buffer that the string class owns, but is not reference counted, because it came from somewhere else) dependent buffers, that is, an underlying buffer that the string class does not own, but that the caller that constructed the string guarantees will outlive the string instance in addition, there is a special string class, ns[c]autostring, that additionally contains an internal 64-unit buffer (intended primarily for use on the stack), leading to a fourth ownership model: storage within an auto string's stack buffer auto strings will prefer reference counting an existing reference-counted buffer over their stack buffer, but will otherwise use their stack buffer for anything that will fit in it.
... nsautostring / nsautocstring- derived from nsstring, a string which owns a 64 code unit buffer in the same storage space as the string itself.
...And 16 more matches
Index
MozillaTechXPCOMIndex
937 tostring no summary!
... 940 tostring no summary!
... 943 tostring no summary!
...And 15 more matches
Bytecode Descriptions
the conversion can call .tostring()/.valueof() methods and can throw.
...the conversion can call .tostring()/.valueof() methods and can throw.
...the conversion can call .tostring()/.valueof() methods and can throw.
...And 11 more matches
JXON - Archive of obsolete content
jxontree.prototype.valueof = function () { return this.keyvalue; }; jxontree.prototype.tostring = function () { return string(this.keyvalue); }; jxontree.prototype.getitem = function (nitem) { if (nlength === 0) { return null; } var ncount = 0; for (var skey in this) { if (ncount === nitem) { return this[skey]; } ncount++; } return null; }; jxontree.prototype.getattribute = function (nattrid) { if (nattrlen === 0 || nattrid + 1 > nattrlen) { return null; } var nattr = 0; for (...
... \*/ function parsetext (svalue) { if (/^\s*$/.test(svalue)) { return null; } if (/^(?:true|false)$/i.test(svalue)) { return svalue.tolowercase() === "true"; } if (isfinite(svalue)) { return parsefloat(svalue); } if (isfinite(date.parse(svalue))) { return new date(svalue); } return svalue; } function objectify (vvalue) { if (vvalue === null) { return new (function() { this.tostring = function() { return "null"; } this.valueof = function() { return null; } })(); } return vvalue instanceof object ?
...|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ function createxml (oobjtree) { function loadobjtree (oparentel, oparentobj) { var vvalue, ochild; if (oparentobj.constructor === string || oparentobj.constructor === number || oparentobj.constructor === boolean) { oparentel.appendchild(onewdoc.createtextnode(oparentobj.tostring())); /* verbosity level is 0 or 1 */ if (oparentobj === oparentobj.valueof()) { return; } } else if (oparentobj.constructor === date) { oparentel.appendchild(onewdoc.createtextnode(oparentobj.togmtstring())); } for (var sname in oparentobj) { if (isfinite(sname)) { continue; } /* verbosity level is 0 */ vvalue = oparentobj[sname]; if (sname === "keyvalue"...
...And 8 more matches
sample2
nature-----" #define ns_cert_header "-----begin certificate-----" #define ns_cert_trailer "-----end certificate-----" /* missing publically from nss versions earlier than 3.13 */ #ifndef sec_error_base #define sec_error_base (-0x2000) typedef enum { sec_error_io = sec_error_base + 0, sec_error_token_not_logged_in = (sec_error_base + 155), sec_error_end_of_list } secerrorcodes; #endif /* port_errortostring introduced in nss 3.13.
... on earlier versions of nss that * don't support error tables, pr_errortostring will return "unknown code".
... */ #ifndef port_errortostring #define port_errortostring(err) pr_errortostring((err), pr_language_i_default) #endif /* sample 6 commands */ typedef enum { generate_csr, add_cert_to_db, save_cert_to_header, encrypt, decrypt, sign, verify, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6, certenc= 7, certvfy= 8, sig = 9 } headertype; /* * print usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s %s %s %s %s %s %s %s %s %s\n\n", progname, " -<g|a|h|e|ds|v> -d <dbdirpath> ", "[-p <dbpwd> | -f <dbpwdfile>] [-z <noisefilename>] [-a <\"\">]", "-s <subject> -r <csr> | ", "-n <nickname> -t <trust> -c <cert> [ -r <csr> -u <issuernickname> [-x <\"\">] -m <serialnumber> ] | ", "-n <nickname> -b <headerfile...
...And 8 more matches
Working with data
// lets create an array of long's var my = ctypes.long.array()([1, 2, 3, 4]); my.tostring(); // this outputs to browser console: `"ctypes.long.array(4)([ctypes.int64("1"), ctypes.int64("2"), ctypes.int64("3"), ctypes.int64("4")])"` my.addressofelement(1).contents; // this outputs `int64 { }` my.addressofelement(1).contents.tostring(); // outputs: `"2"` // now this is how to get the array of long's cast to array of int's var mycasted = ctypes.cast(my.address(), ctypes.int.array(my.le...
...ngth).ptr).contents; mycasted.tostring(); // this outputs to browser console: `"ctypes.int.array(4)([1, 2, 3, 4])"` mycasted.addressofelement(1).contents; // this outputs `2` mycasted.addressofelement(1).contents.tostring(); // outputs: `"2"` source of this, and to see wrong ways of casting, and explanation on why this is the right way to cast an array (explained by matching constructor's) see here: githubgist :: _ff-addon-tutorial-jsctypes_castingarrays data and pointers a cdata object represents a c value in memory.
... you can work around this by serializing these values using the tostring() method and comparing using the resulting string.
...And 8 more matches
Type conversion
pes.char.array(10)(); var somecfunction = library.declare("somecfunction", ctypes.default_abi, ctypes.void_t, ctypes.char.ptr); somecfunction(buffer); // here ctypes.char.array(10)() is converted to ctypes.char.ptr type implicit conversion can be tested in the following way: var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v = 1; console.log(mystruct.v.tostring()); // 'true' boolean type target type source converted value ctypes.bool js boolean src js number (0 or 1) if src == 0: false if src == 1: true var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v = true; console.log(mystruct.v.tostring()); // 'true' mystruct.v = false; console.log(mystruct.v.tostr...
...ing()); // 'false' mystruct.v = 1; console.log(mystruct.v.tostring()); // 'true' mystruct.v = 0; console.log(mystruct.v.tostring()); // 'false' mystruct.v = 10; // throws error mystruct.v = "a"; // throws error integer types target type source converted value ctypes.char16_t js string (only if its length == 1) src.charcodeat(0) any integer types js number (only if fits to the size) src js boolean if src == true: 1 if src == false: 0 var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.char16_t } ])(); mystruct.v = 0x41; console.log(mystruct.v.tostring()); // "a" mystruct.v = true; console.log(mystruct.v.tostring()); // "\x01" mystruct.v = "x"; console.log(mystruct.v.tostring()); // "x" my...
...struct.v = "xx"; // throws error var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.int16_t } ])(); mystruct.v = 0x41; console.log(mystruct.v.tostring()); // 65 mystruct.v = true; console.log(mystruct.v.tostring()); // 1 mystruct.v = "x"; // throws error integer/float types are implicitly convertible if any data of source type could be representable in the target type.
...And 7 more matches
Index - Web APIs
WebAPIIndex
1700 htmlhyperlinkelementutils.tostring() api, experimental, htmlhyperlinkelementutils, location, method, stringifier, url api the htmlhyperlinkelementutils.tostring() stringifier method returns a usvstring containing the whole url.
... 3585 range.tostring() api, dom, method, range, stringifier the range.tostring() method is a stringifier returning the text of the range.
... 3917 selection.tostring() api, experimental, html editing, method, reference, selection the selection.tostring() method returns a string currently being represented by the selection object, i.e.
...And 6 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
m; secoidtag algtag; pk11rsagenparams rsaparams; void *params; seckeyprivatekey *privkey = null; secstatus rv; unsigned char randbuf[blocksize + 1]; rv = generaterandom(randbuf, blocksize); if (rv != secsuccess) { fprintf(stderr, "error while generating the random numbers : %s\n", port_errortostring(rv)); goto cleanup; } pk11_randomupdate(randbuf, blocksize); switch (keytype) { case rsakey: rsaparams.keysizeinbits = size; rsaparams.pe = publicexponent; mechanism = ckm_rsa_pkcs_key_pair_gen; algtag = sec_oid_pkcs1_md5_with_rsa_encryption; params ...
...gnaturealgorithmoidtag(privkey->keytype, hashalgtag); if (algid == sec_oid_unknown) { pr_fprintf(pr_stderr, "unknown key or hash type for issuer.\n"); goto cleanup; } rv = secoid_setalgorithmid(arena, &cert->signature, algid, 0); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not set signature algorithm id.\n%s\n", port_errortostring(rv)); goto cleanup; } /* we only deal with cert v3 here */ *(cert->version.data) = 2; cert->version.len = 1; der.len = 0; der.data = null; dummy = sec_asn1encodeitem (arena, &der, cert, sec_asn1_get(cert_certificatetemplate)); if (!dummy) { pr_fprintf(pr_stderr, "could not encode certificate.\n"); ...
...ort_arenazalloc (arena, sizeof (secitem)); if (result == null) { pr_fprintf(pr_stderr, "could not allocate item for certificate data.\n"); goto cleanup; } rv = sec_dersigndata(arena, result, der.data, der.len, privkey, algid); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not sign encoded certificate data : %s\n", port_errortostring(rv)); /* result allocated out of the arena, it will be freed * when the arena is freed */ result = null; goto cleanup; } cert->dercert = *result; cleanup: if (caprivatekey) { seckey_destroyprivatekey(caprivatekey); } return result; } /* * makev1cert */ static certcertificate * makev1cert(certcertdbhandle *handle...
...And 5 more matches
Index
77 js::tostring jsapi reference, reference, référence(2), spidermonkey js::tostring returns a string representation of a javascript value.
...each version has a name, which is a string used by js_stringtoversion and js_versiontostring.
...if v is not a string, it is converted to a string as if by calling js_valuetostring.
...And 4 more matches
context-menu - Archive of obsolete content
this item implements the aforementioned search example: var cm = require("sdk/context-menu"); cm.item({ label: "search google", context: cm.selectioncontext(), contentscript: 'self.on("context", function () {' + ' var text = window.getselection().tostring();' + ' if (text.length > 20)' + ' text = text.substr(0, 20) + "...";' + ' return "search google for " + text;' + '});' }); the "context" listener gets the window's current selection, truncating it if it's too long, and includes it in the returned string.
...it must either be a string or an object that implements tostring().
...it must be either a string or an object that implements tostring().
...And 2 more matches
StringView - Archive of obsolete content
noffset : 0, ntranscrtype = 15; if (sencoding) { this.encoding = sencoding.tostring(); } encswitch: switch (this.encoding) { case "utf-8": fputoutptcode = stringview.pututf8charcode; fgetoutptchrsize = stringview.getutf8charlength; ftaview = uint8array; break encswitch; case "utf-16": fputoutptcode = stringview.pututf16charcode; fgetoutptchrsize = stringview.getutf16charlength; ftaview = uint16array; break encswitch; ...
...nchrlen + nrawidx : asource.length; for (nrawidx; nrawidx < nrawend; nrawidx++) { if (!othat) { fcallback(asource[nrawidx], nrawidx, nrawidx, asource); } else { fcallback.call(othat, asource[nrawidx], nrawidx, nrawidx, asource); } } } }; stringview.prototype.valueof = stringview.prototype.tostring = function () { if (this.encoding !== "utf-8" && this.encoding !== "utf-16") { /* ascii, utf-32 or binarystring to domstring */ return string.fromcharcode.apply(null, this.rawdata); } var fgetcode, fgetincr, sview = ""; if (this.encoding === "utf-8") { fgetincr = stringview.getutf8charlength; fgetcode = stringview.loadutf8charcode; } else if (this.encoding === "utf-16...
...stringview.tobase64(optional boolean wholebuffer); stringview stringview.subview(unsigned long characteroffset, optional unsigned long characterslength); void stringview.foreachchar(function callback, optional object thisobject, optional unsigned long characteroffset, optional unsigned long characterslength); domstring stringview.valueof(); domstring stringview.tostring(); properties overview attribute type description encoding read only domstring a string expressing the encoding type.
...And 2 more matches
The new nsString class implementation (1999) - Archive of obsolete content
in addition to the nsstrimpl api shown above, nsstring, nsautostring and nscstring all offer additional api's (that all degrade to those found in nsstrimpl) for construction, searching and comparison.
...nsautostring we still offer an nsautostring that provides its own stack based buffer.
...an additional improvement has been made to nsautostring that allows it to use an arbitrarily sized stack based buffer rather than its own internal buffer.
...And 2 more matches
How to embed the JavaScript engine
jsautocompartment ac(cx, global); js_initstandardclasses(cx, global); const char *script = "'hello'+'world, it is '+new date()"; const char *filename = "noname"; int lineno = 1; bool ok = js_evaluatescript(cx, global, script, strlen(script), filename, lineno, rval.address()); if (!ok) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); } js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); return 0; } spidermonkey 31 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object.
...mpartment jsautocompartment ac(cx, global); js_initstandardclasses(cx, global); const char *script = "'hello'+'world, it is '+new date()"; const char *filename = "noname"; int lineno = 1; bool ok = js_evaluatescript(cx, global, script, strlen(script), filename, lineno, &rval); if (!ok) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); } js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); return 0; } spidermonkey 38 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object.
...standardclasses(cx, global); const char *script = "'hello'+'world, it is '+new date()"; const char *filename = "noname"; int lineno = 1; js::compileoptions opts(cx); opts.setfileandline(filename, lineno); bool ok = js::evaluate(cx, global, opts, script, strlen(script), &rval); if (!ok) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); } js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); return 0; } spidermonkey 45 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" #include "js/initialization.h" /* the class of the global object.
...And 2 more matches
XPCOM primitive
(however, if you are designing that kind of api today, you should probably use nsivariant instead.) idl data type interface component idl nsidptr nsisupportsid @mozilla.org/supports-id;1 [scriptable, uuid(d18290a0-4a1c-11d3-9890-006008962422)] interface nsisupportsid : nsisupportsprimitive { attribute nsidptr data; string tostring(); }; astring nsisupportsstring @mozilla.org/supports-string;1 [scriptable, uuid(d79dc970-4a1c-11d3-9890-006008962422)] interface nsisupportsstring : nsisupportsprimitive { attribute astring data; wstring tostring(); }; prbool nsisupportsprbool @mozilla.org/supports-prbool;1 [scriptable, uuid(ddc3b490-4a1c-11d3-9890-006008962422)] interface nsisupportsprbool : nsisupportsprimitive { ...
... attribute prbool data; string tostring(); }; pruint8 nsisupportspruint8 @mozilla.org/supports-pruint8;1 [scriptable, uuid(dec2e4e0-4a1c-11d3-9890-006008962422)] interface nsisupportspruint8 : nsisupportsprimitive { attribute pruint8 data; string tostring(); }; pruint16 nsisupportspruint16 @mozilla.org/supports-pruint16;1 [scriptable, uuid(dfacb090-4a1c-11d3-9890-006008962422)] interface nsisupportspruint16 : nsisupportsprimitive { attribute pruint16 data; string tostring(); }; pruint32 nsisupportspruint32 @mozilla.org/supports-pruint32;1 [scriptable, uuid(e01dc470-4a1c-11d3-9890-006008962422)] interface nsisupportspruint32 : nsisupportsprimitive { attribute pruint32 data; string tostring(); }; pruint64 nsisupportspruint64 @mozilla.org/supports-pruint64;1 [scr...
...iptable, uuid(e13567c0-4a1c-11d3-9890-006008962422)] interface nsisupportspruint64 : nsisupportsprimitive { attribute pruint64 data; string tostring(); }; prtime nsisupportsprtime @mozilla.org/supports-prtime;1 [scriptable, uuid(e2563630-4a1c-11d3-9890-006008962422)] interface nsisupportsprtime : nsisupportsprimitive { attribute prtime data; string tostring(); }; char nsisupportschar @mozilla.org/supports-char;1 [scriptable, uuid(e2b05e40-4a1c-11d3-9890-006008962422)] interface nsisupportschar : nsisupportsprimitive { attribute char data; string tostring(); }; print16 nsisupportsprint16 @mozilla.org/supports-print16;1 [scriptable, uuid(e30d94b0-4a1c-11d3-9890-006008962422)] interface nsisupportsprint16 : nsisupportsprimitive { attribute print16 data; string to...
...And 2 more matches
CData
method overview methods available on all cdata objects cdata address() string tosource() string tostring() properties properties of all cdata objects property type description constructor ctype the data type of the cdata object, as a ctype.
... in theory, in other words, the following javascript expression should return a copy of the original cdata object: eval(dataobject.tosource()); tostring() returns a string identifying the data.
... string tostring(); parameters none.
...And 2 more matches
Object.create() - JavaScript
differences quickly become apparent: > "oco is: " + oco // shows "oco is: [object object]" > "ocn is: " + ocn // throws error: cannot convert object to primitive value testing just a few of the many most basic built-in functions shows the magnitude of the problem more clearly: > alert(oco) // shows [object object] > alert(ocn) // throws error: cannot convert object to primitive value > oco.tostring() // shows [object object] > ocn.tostring() // throws error: ocn.tostring is not a function > oco.valueof() // shows {} > ocn.valueof() // throws error: ocn.valueof is not a function > oco.hasownproperty("p") // shows "true" > ocn.hasownproperty("p") // throws error: ocn.hasownproperty is not a function > oco.constructor // shows "object() { [native code] }" > ocn.constructor // shows "undefin...
... adding the missing object-method directly from the standard-object does not work: ocn = object.create( null ); // create "null" object (same as before) ocn.tostring = object.tostring; // since new object lacks method then try assigning it directly from standard-object > ocn.tostring // shows "tostring() { [native code] }" -- missing method seems to be there now > ocn.tostring == object.tostring // shows "true" -- method seems to be same as the standard object-method > ocn.tostring() // error: function.prototype.tostring requires that 'this' be a function ...
... adding the missing object-method directly to new object's "prototype" does not work either, since the new object does not have a real prototype (which is really the cause of all these problems) and one cannot be directly added: ocn = object.create( null ); // create "null" object (same as before) ocn.prototype.tostring = object.tostring; // error: cannot set property 'tostring' of undefined ocn.prototype = {}; // try to create a prototype ocn.prototype.tostring = object.tostring; // since new object lacks method then try assigning it from standard-object > ocn.tostring() // error: ocn.tostring is not a function adding the missing object-method by using the standard-object as new object's prototype does not work either: ocn = object.create( null ); // crea...
...And 2 more matches
Symbol - JavaScript
symbol.tostringtag a string value used for the default description of an object.
... used by object.prototype.tostring().
... symbol.prototype.tostring() returns a string containing the description of the symbol.
...And 2 more matches
Finding window handles - Archive of obsolete content
foregroundwindow( * __in_ hwnd hwnd * ); */ var setforegroundwindow = user32.declare('setforegroundwindow', ctypes.winapi_abi, ctypes.bool, // return bool ctypes.voidptr_t // hwnd ); var hwnd = ctypes.voidptr_t(ctypes.uint64(hwndstring)); var rez_setforegroundwindow = setforegroundwindow(hwnd); console.log('rez_setforegroundwindow:', rez_setforegroundwindow, rez_setforegroundwindow.tostring()); user32.close(); mac os x objective-c components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) ...
...coa/reference/applicationkit/classes/nsapplication_class/index.html#//apple_ref/occ/instp/nsapplication/orderfront: * [nswindowptr orderfront:nil] */ var orderfront = sel_registername('orderfront:'); var nswindowptr = ctypes.voidptr_t(ctypes.uint64(nswindowstring)); var rez_orderfront = objc_msgsend(nswindowptr, orderfront, nil); console.log('rez_orderfront:', rez_orderfront, rez_orderfront.tostring()); objc.close(); unix under unix systems, the nativehandle holds a string address to a gdkwindow* (the asterik/star means pointer).
...on.html#gdk-x11-get-server-time var gdk_x11_get_server_time = gdk.declare('gdk_x11_get_server_time', ctypes.default_abi, guint32, gdkwindow.ptr); var browserwindow_madeintogdkwinptr = gdkwindow.ptr(ctypes.uint64(gdkwindowptrstring)); var gptr = gpointer(); var rez_gwgud = gdk_window_get_user_data(browserwindow_madeintogdkwinptr, gptr.address()); console.info('rez_gwgud:', rez_gwgud, /*rez_gwgud.tostring(),*/ uneval(rez_gwgud)); // return is void so cant do .tostring on it var browserwindow_madeintogtkwindowptr = ctypes.cast(gptr, gtkwindow.ptr); // focusing window this way is better, so it maintains proper history in case you or some other app want to focus "most recent window" by timestamp // var rez_gst = gdk_x11_get_server_time(browserwindow_madeintogdkwinptr); // console.info('rez_gst:', r...
...dkdrawable.ptr); var browserwindow_madeintogdkwinptr = gdkwindow.ptr(ctypes.uint64(gdkwindowptrstring)); var browserwindow_madeintogdkdrawable = ctypes.cast(browserwindow_madeintogdkwinptr, gdkdrawable.ptr); var browserwindow_madeintoxid = gdk_x11_drawable_get_xid(browserwindow_madeintogdkdrawable); console.info('browserwindow_madeintoxid:', browserwindow_madeintoxid, browserwindow_madeintoxid.tostring(), uneval(browserwindow_madeintoxid)); // the code to focus the window is soon to come, its long and messy it needs to be made into a simple readable good for example.
String Quick Reference - Archive of obsolete content
old way: use nsstring& and nscstring& void mymethod(const nsstring& input, nsstring& output); new way: use nsastring& and nsacstring& void mymethod(const nsastring& input, nsastring& output); substrings what: get direct references to string fragments why: avoid making multiple copies of the string old way: use a bunch of nsautostrings, and use left(), right() and mid() to grab a segment of a string: // get an 8-character string starting at the 4th position nsautostring leftside; str.left(leftside, 12); nsautostring middle; leftside.right(middle, 8); new way: use substring() to grab a direct reference to those characters: // get an 8-character string starting at the 4th position const nsastring& middle = substring(str, 4, 8...
...old way: use nsautostring and assignwithconversion() nsautostring widestring; widestring.assignwithconversion("some string"); callwidefunction(widestring); // use widestring again, but need a const prunichar* callwidewithflatstring(widestring.get()) nsautostring widestring2; widestring2.assignwithconversion("another string"); callwidefunction(widestring2); new way: use ns_literal_string or ns_named_literal_string // pre-declare the variable if you'll use it multiple times ns_named_literal_string(widestring, "some string"); callwidefunction(widestring); // use widestring again, but need a const prunichar* callwidewithflatst...
...note: may involve changing existing apis old way: wrap with nscautostring() // foo is a prunichar* string // call // void handlestring(const nsstring& str); handlestring(nsautostring(foo)); new way: wrap with nsdependentstring // foo is a prunichar* string // fix caller to be // void handlestring(const nsastring& str); handlestring(nsdependentstring(foo)); stack-based strings what: use of special stack-oriented classes why: to avoid excess heap allocations and memory ...
... right: use nsautostring/nscautostring and nsxpidlstring/nsxpidlcstring // call getstringvalue(nsastring& out); nsautostring value; // 64-character buffer on stack getstringvalue(value); // call getstringvalue(char** out); nsxpidlcstring result; getstringvalue(getter_copies(result)); // result will free automatically original document information author: alec flett last updated date: april 30, 2003 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons lice...
LiveConnect Overview - Archive of obsolete content
java.lang.string the object is unwrapped, the tostring method of the unwrapped java object is called, and the result is returned as a new instance of java.lang.string.
... java.lang.string the object is unwrapped, the tostring method of the unwrapped java object is called, and the result is returned as a new instance of java.lang.string.
... java.lang.string the object is unwrapped, the tostring method of the unwrapped object is called, and the result is returned as a new instance of java.lang.string.
... a java object of any other class is converted to a javascript wrapper, which can be used to access methods and fields of the java object: converting this wrapper to a string calls the tostring method on the original object.
Arrays - Learn web development
try the following: let mynewstring = myarray.join(','); mynewstring; another way of converting an array to a string is to use the tostring() method.
... tostring() is arguably simpler than join() as it doesn't take a parameter, but more limiting.
... with join() you can specify different separators, whereas tostring() always uses a comma.
... (try running step 4 with a different character than a comma.) let dognames = ['rocket','flash','bella','slugger']; dognames.tostring(); // rocket,flash,bella,slugger adding and removing array items we've not yet covered adding and removing array items — let us look at this now.
TypeScript support in Svelte - Learn web development
update your localstore.ts file like this: // localstore.ts import { writable } from 'svelte/store' import type { jsonvalue } from './types/json.type' export const localstore = (key: string, initial: jsonvalue) => { // receives the key of the local storage and an initial value const tostring = (value: jsonvalue) => json.stringify(value, null, 2) // helper function const toobj = json.parse // helper function if (localstorage.getitem(key) === null) { // item not present in local storage localstorage.setitem(key, tostring(initial)) // initialize local storage with initial val...
...ue } const saved = toobj(localstorage.getitem(key)) // convert to object const { subscribe, set, update } = writable(saved) // create the underlying writable store return { subscribe, set: (value: jsonvalue) => { localstorage.setitem(key, tostring(value)) // save also to local storage as a string return set(value) }, update } } now if we try to create a localstore with something that cannot be converted to json via json.stringify(), for example an object with a function as a property, vs code/validate will complain about it: and best of all, it will even work with the $store auto-subscription syntax.
... our localstore.ts file will end up like this — try the new code now in your version: // localstore.ts import { writable } from 'svelte/store' import type { jsonvalue } from './types/json.type' export const localstore = <t extends jsonvalue>(key: string, initial: t) => { // receives the key of the local storage and an initial value const tostring = (value: t) => json.stringify(value, null, 2) // helper function const toobj = json.parse // helper function if (localstorage.getitem(key) === null) { // item not present in local storage localstorage.setitem(key, tostring(initial)) // initialize local storage with initial val...
...ue } const saved = toobj(localstorage.getitem(key)) // convert to object const { subscribe, set, update } = writable<t>(saved) // create the underlying writable store return { subscribe, set: (value: t) => { localstorage.setitem(key, tostring(value)) // save also to local storage as a string return set(value) }, update } } and thanks to generic type inference, typescript already knows that our $todos store should contain an array of todotype: once again, if we wanted to be explicit about it, we could do so in the stores.ts file like this: const initialtodos: todotype[] = [ { id: 1, name: 'visit mdn web docs', completed: true }, { id: 2, name: 'complete the svelte tutorial', complet...
Enc Dec MAC Output Public Key as CSR
ne ns_certreq_header "-----begin new certificate request-----" #define ns_certreq_trailer "-----end new certificate request-----" typedef enum { gen_csr, encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6 } headertype; /* this is conditionalized because port_errortostring was introduced with nss 3.13.
... * though pr_errortostring was available, support for it in nss wasn't.
... */ #ifndef port_errortostring #ifndef sec_error_base #define sec_error_base (-0x2000) #define port_errortostring(err) pr_errortostring((err), pr_language_i_default) #endif #endif /* * print usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -s -r -i -o \n\n", progname); fprintf(stderr, "%-20s specify 'g' for generating rsa keypair for wrapping\n\n", "g"); fprintf(stderr, "%-20s specify 'e' for encrypt operation\n\n", "e"); fprintf(stderr, "%-20s specify 'd' for decrypt operation\n\n", "d"); ...
... mechanism; secoidtag algtag; pk11rsagenparams rsaparams; void *params; seckeyprivatekey *privkey = null; secstatus rv; unsigned char randbuf[blocksize + 1]; rv = generaterandom(randbuf, blocksize); if (rv != secsuccess) { fprintf(stderr, "error while generating the random numbers : %s\n", port_errortostring(rv)); goto cleanup; } pk11_randomupdate(randbuf, blocksize); switch (keytype) { case rsakey: rsaparams.keysizeinbits = size; rsaparams.pe = publicexponent; mechanism = ckm_rsa_pkcs_key_pair_gen; algtag = sec_oid_pkcs1_md5_with_rsa_encryption; params = ...
Tutorial: Embedding Rhino
printing the result the code system.out.println(cx.tostring(result)); prints the result of evaluating the script (contained in the variable result).
...the tostring method converts any javascript value to a string.
...f("my args") = my arg using javascript variables to print out the value of x, we add the following code: object x = scope.get("x", scope); if (x == scriptable.not_found) { system.out.println("x is not defined."); } else { system.out.println("x = " + context.tostring(x)); } calling javascript functions to get the function f, call it, and print the result, we add this code: object fobj = scope.get("f", scope); if (!(fobj instanceof function)) { system.out.println("f is undefined or not a function."); } else { object functionargs[] = { "my arg" }; function f = (function)fobj; object result = f.call(cx, scope, scope, functionargs); string...
... report = "f('my args') = " + context.tostring(result); system.out.println(report); } javascript host objects defining host objects custom host objects can implement special javascript features like dynamic properties.
Window.getSelection() - Web APIs
when cast to string, either by appending an empty string ("") or using selection.tostring(), this object returns the text selected.
... examples function foo() { var selobj = window.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's tostring() method is called and the returned value is passed to the function.
... in the above example, selobj.tostring() is automatically called when it is passed to window.alert().
...to use a selection object as a string, call its tostring() method directly: var selectedtext = selobj.tostring(); selobj is a selection object.
XMLSerializer - Web APIs
the xmlserializer interface provides the serializetostring() method to construct an xml string representing a dom tree.
... methods serializetostring() returns the serialized subtree of a string.
... var s = new xmlserializer(); var d = document; var str = s.serializetostring(d); savexml(str); this involves creating a new xmlserializer object, then passing the document to be serialized into serializetostring(), which returns the xml equivalent of the document.
... var inp = document.createelement('input'); var xmls = new xmlserializer(); var inp_xmls = xmls.serializetostring(inp); // first convert dom node into a string // insert the newly created node into the document's body document.body.insertadjacenthtml('afterbegin', inp_xmls); the code creates a new <input> element by calling document.createelement(), then serializes it into xml using serializetostring().
RangeError: radix must be an integer - JavaScript
the javascript exception "radix must be an integer at least 2 and no greater than 36" occurs when the optional radix parameter of the number.prototype.tostring() or the bigint.prototype.tostring() method was specified and is not between 2 and 36.
... message rangeerror: invalid argument (edge) rangeerror: radix must be an integer at least 2 and no greater than 36 (firefox) rangeerror: tostring() radix argument must be between 2 and 36 (chrome) error type rangeerror what went wrong?
... the optional radix parameter of the number.prototype.tostring() or the bigint.prototype.tostring() method was specified.
... examples invalid cases (42).tostring(0); (42).tostring(1); (42).tostring(37); (42).tostring(150); // you cannot use a string like this for formatting: (12071989).tostring('mm-dd-yyyy'); valid cases (42).tostring(2); // "101010" (binary) (13).tostring(8); // "15" (octal) (0x42).tostring(10); // "66" (decimal) (100000).tostring(16) // "186a0" (hexadecimal) ...
Array - JavaScript
let arr = ['this is the first element', 'this is the second element', 'this is the last element'] console.log(arr[0]) // logs 'this is the first element' console.log(arr[1]) // logs 'this is the second element' console.log(arr[arr.length - 1]) // logs 'this is the last element' array elements are object properties in the same way that tostring is a property (to be specific, however, tostring() is a method).
... the 2 in years[2] is coerced into a string by the javascript engine through an implicit tostring conversion.
... array.prototype.tostring() returns a string representing the array and its elements.
... overrides the object.prototype.tostring() method.
Communicating using "postMessage" - Archive of obsolete content
e constructor: panel = require("sdk/panel").panel({ onmessage: function(contentscriptmessage) { // handle message from the content script } }); message events versus user-defined events you can use message events as an alternative to user-defined events: var pagemodscript = "window.addeventlistener('mouseover', function(event) {" + " self.postmessage(event.target.tostring());" + "}, false);"; var pagemod = require('sdk/page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.on('message', function(message) { console.log('mouseover: ' + message); }); } }); the reason to prefer user-defined events is that as soon as you need to send more than one type of message, then both sen...
...now we have to embed the event type in the message payload, and implement a switch function in the receiver to dispatch the message: var pagemodscript = "window.addeventlistener('mouseover', function(event) {" + " self.postmessage({" + " kind: 'mouseover'," + " element: event.target.tostring()" + " });" + "}, false);" + "window.addeventlistener('mouseout', function(event) {" + " self.postmessage({" + " kind: 'mouseout'," + " element: event.target.tostring()" + " });" + " }, false);" var pagemod = require('sdk/page-mo...
...e.log('mouseover: ' + message.element); break; case 'mouseout': console.log('mouseout: ' + message.element); break; } }); } }); implementing the same add-on with user-defined events is shorter and more readable: var pagemodscript = "window.addeventlistener('mouseover', function(event) {" + " self.port.emit('mouseover', event.target.tostring());" + "}, false);" + "window.addeventlistener('mouseout', function(event) {" + " self.port.emit('mouseout', event.target.tostring());" + "}, false);"; var pagemod = require('sdk/page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.port.on('mouseover', func...
Add a Context Menu Item - Archive of obsolete content
when it's clicked, the selection is sent to the main add-on code, which just logs it: var contextmenu = require("sdk/context-menu"); var menuitem = contextmenu.item({ label: "log selection", context: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' + ' var text = window.getselection().tostring();' + ' self.postmessage(text);' + '});', onmessage: function (selectiontext) { console.log(selectiontext); } }); try it: run the add-on, load a web page, select some text and right-click.
...ypically you'd store the image in your add-on's "data" directory, and construct the url using self.data.url(): var self = require("sdk/self"); var contextmenu = require("sdk/context-menu"); var menuitem = contextmenu.item({ label: "log selection", context: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' + ' var text = window.getselection().tostring();' + ' self.postmessage(text);' + '});', image: self.data.url("icon-16.png"), onmessage: function (selectiontext) { console.log(selectiontext); } }); adding an access key new in firefox 35.
...pressing the key selects the option when the context menu is open: var contextmenu = require("sdk/context-menu"); var menuitem = contextmenu.item({ label: "log selection", context: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' + ' var text = window.getselection().tostring();' + ' self.postmessage(text);' + '});', accesskey: "l", onmessage: function (selectiontext) { console.log(selectiontext); } }); learning more to learn more about the context-menu module, see the context-menu api reference.
Creating Reusable Modules - Archive of obsolete content
we can adapt it like this: var {cc, ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } function md5file(path) { var f = cc["@mozilla.org/file/local;1"] .createinstance(ci.nsilocalfile); f.initwithpath(path); var istream = cc["@mozilla.org/network/file-input-stream;1"] .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstan...
...c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } putting it together the complete add-on adds a button to firefox: when the user clicks the button, we ask them to select a file, compute the hash, and log the hash to the console: var {cc, ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } function md5file(path) { var f = cc["@mozilla.org/file/local;1"] .createinstance(ci.nsilocalfile); f.initwithpath(path); var istream = cc["@mozilla.org/network/file-input-stream;1"] .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstan...
...copy the hashing code there, and add this line at the end: exports.hashfile = md5file; the complete file looks like this: var {cc, ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } function md5file(path) { var f = cc["@mozilla.org/file/local;1"] .createinstance(ci.nsilocalfile); f.initwithpath(path); var istream = cc["@mozilla.org/network/file-input-stream;1"] .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstan...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
web script example <script type="application/javascript"> <!-- function install (aevent) { for (var a = aevent.target; a.href === undefined;) a = a.parentnode; var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } } }; installtrigger.install(params); return false; } //--> </script> <a href="http://www.example.com/foo.xpi" iconurl="http://www.example.com/foo.png" hash="sha1:28857e60d043447c5f4550853f2d40770b326a13" onclick="return install(event);">install extension!</a> let's go through this piece by piece.
... the install first creates a parameter block: var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } }; this specifies the display name (foo) for use in the confirmation dialog, the url to the extension (which is the link href, recall), the icon url to display in the confirmation dialog, a hash of the xpi file contents (to protect against corrupted downloads), and a tostring function which will allow this code to work with versions of firefox 0.8 and earlier.
... tostring() the tostring() property should return the xpi url, for compatibility with firefox browsers older than version 1.0, and other applications such as seamonkey.
jspage - Archive of obsolete content
turn($type(c)===b); };}};(function(){var a={array:array,date:date,function:function,number:number,regexp:regexp,string:string};for(var h in a){new native({name:h,initialize:a[h],protect:true}); }var d={"boolean":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=new native({name:"hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getclean()); }for(var b in a){th...
...((c=="array"||c=="collection"||c=="arguments")?array.flatten(this[b]):this[b]); }return d;},hextorgb:function(b){if(this.length!=3){return null;}var a=this.map(function(c){if(c.length==1){c+=c;}return c.toint(16);});return(b)?a:"rgb("+a+")"; },rgbtohex:function(d){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!d){return"transparent";}var b=[];for(var a=0;a<3;a++){var c=(this[a]-0).tostring(16); b.push((c.length==1)?"0"+c:c);}return(d)?b:"#"+b.join("");}});function.implement({extend:function(a){for(var b in a){this[b]=a[b];}return this;},create:function(b){var a=this; b=b||{};return function(d){var c=b.arguments;c=(c!=undefined)?$splat(c):array.slice(arguments,(b.event)?1:0);if(b.event){c=[d||window.event].extend(c); }var e=function(){return a.apply(b.bind||null,c);};if(b.delay){ret...
...omplete"].contains(document.readystate))?b():arguments.callee.delay(50); })();}else{document.addevent("domcontentloaded",b);}}})();var json=new hash(this.json&&{stringify:json.stringify,parse:json.parse}).extend({$specialchars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replacechars:function(a){return json.$specialchars[a]||"\\u00"+math.floor(a.charcodeat()/16).tostring(16)+(a.charcodeat()%16).tostring(16); },encode:function(b){switch($type(b)){case"string":return'"'+b.replace(/[\x00-\x1f\\"]/g,json.$replacechars)+'"';case"array":return"["+string(b.map(json.encode).clean())+"]"; case"object":case"hash":var a=[];hash.each(b,function(e,d){var c=json.encode(e);if(c){a.push(json.encode(d)+":"+c);}});return"{"+a+"}";case"number":case"boolean":return string(b); case f...
Processing XML with E4X - Archive of obsolete content
this node has one attribute, type, which can be accessed and updated in a number of ways: alert(languages.@type); // alerts "dynamic" languages.@type = "agile"; alert(languages.@type); // alerts "agile" alert(languages.tostring()); /* alerts: <languages type="agile"><lang>javascript</lang><lang>python</lang></languages> */ note that if one wishes to make comparisons of retrieved attributes with other strings, it is necessary to convert the attribute first, even though the attribute may be converted to a string when used in other contexts (such as insertion into a textbox).
... if (languages.@type.tostring() === 'agile') { ...
... we can iterate through the matching elements like so: for (var i = 0; i < languages.lang.length(); i++) { alert(languages.lang[i].tostring()); } here we are using identical syntax to that used to access numbered items in an array.
JSObject - Archive of obsolete content
tostring converts a jsobject to a string.
... declaration public void setslot(int index, object value) tostring method.
... overrides: tostring in class java.lang.object declaration public string tostring() ...
Working with Svelte stores - Learn web development
give it the following content: import { writable } from 'svelte/store'; export const localstore = (key, initial) => { // receives the key of the local storage and an initial value const tostring = (value) => json.stringify(value, null, 2) // helper function const toobj = json.parse // helper function if (localstorage.getitem(key) === null) { // item not present in local storage localstorage.setitem(key, tostring(initial)) // initialize local storage with initial value } const saved = toobj(localstorage.getit...
...em(key)) // convert to object const { subscribe, set, update } = writable(saved) // create the underlying writable store return { subscribe, set: (value) => { localstorage.setitem(key, tostring(value)) // save also to local storage as a string return set(value) }, update } } our localstore will be a function that when executed initially reads its content from web storage, and returns an object with three methods: subscribe(), set(), and update().
... we use the localstorage.getitem(key) and localstorage.setitem(key, value) methods to read and write information to web storage, and the tostring() and toobj() (which uses json.parse()) helper functions to convert the values.
Dict.jsm
method overview dict copy(); boolean del(string akey); object get(string akey, [optional] object adefault); boolean has(string akey); array listitems(); array listkeys(); array listvalues(); void set(string akey, object avalue); string tojson(); string tostring(); properties attribute type description count number the number of items in the dictionary.
... tostring() returns a string representation of the dictionary.
... string tostring(); parameters none.
NetUtil.jsm
method overview nsiasyncstreamcopier asynccopy(nsiinputstream asource, nsioutputstream asink, [optional] acallback) void asyncfetch(asource, acallback) nsichannel newchannel(awhattoload, [optional] aorigincharset, [optional] nsiuri abaseuri) nsiuri newuri(atarget, [optional] aorigincharset, [optional] nsiuri abaseuri) string readinputstreamtostring(ainputstream, acount, aoptions) attributes attribute type description ioservice nsiioservice returns a reference to nsiioservice.
... readinputstreamtostring() reads a given number of bytes from an input stream, returning a string containing those bytes.
... string readinputstreamtostring( ainputstream, acount, aoptions ); parameters ainputstream the input stream from which to read the data.
SourceMap.jsm
sourcemapgenerator.prototype.tostring() renders the source map being generated to a string.
... sourcenode.prototype.tostring() return the string representation of this source node.
... sourcenode.prototype.tostringwithsourcemap(startofsourcemap) returns the string representation of this tree of source nodes, plus a sourcemapgenerator which contains all the mappings between the generated and original sources.
Mozilla DOM Hacking Guide
domclassinfo does almost everything for you, from prototypes to implementing a default tostring() method on your object.
...the requirements include that the global constructor domimplementation be accessible, that the tostring() method called on an instance of a domimplementation return "domimplementation", and that it implements the following methods: hasfeature() (dom1), createdocumenttype() and createdocument() (dom2).
...the second step is to map .location to .location.href in nswindowsh::setproperty() if (str == slocation_id) { // setting the location property jsstring *val = ::js_valuetostring(cx, *vp); ns_ensure_true(val, ns_error_unexpected); // convert the value assigned to location (i.e.
JSVersion
the functions js_getversion, js_setversion, js_stringtoversion, and js_versiontostring use these values.
...each version has a name, which is a string used by js_stringtoversion and js_versiontostring.
...2 edition 5 "ecmav5" jsversion_default 0 latest javascript version, but omitting web-incompatible extensions "default" jsversion_unknown -1 unknown javascript version null jsversion_latest jsversion_ecma_5 latest javascript version null see also mxr id search for jsversion js_getversion js_setversion js_stringtoversion js_versiontostring bug 824312 ...
JSAPI reference
jsapi 27 js_getoptions obsolete since jsapi 27 js_toggleoptions obsolete since jsapi 27 enum jsversion jsversion_ecma_3 jsversion_1_6 jsversion_1_7 jsversion_1_8 jsversion_ecma_5 jsversion_default jsversion_unknown jsversion_latest js_getimplementationversion js_getversion js_setversionforcompartment added in spidermonkey 31 js_stringtoversion js_versiontostring js_setversion obsolete since jsapi 25 js::currentglobalornull added in spidermonkey 31 js_getglobalforscopechain obsolete since jsapi 25 js_getglobalobject obsolete since jsapi 24 js_setglobalobject obsolete since jsapi 25 js_initclass js_initstandardclasses js_resolvestandardclass js_enumeratestandardclasses js_enumerateresolvedstandardclasses obsolete since jsapi 24 ...
...for example, js_valuetostring(cx, obj) may call obj.tostring().
... js::toboolean added in spidermonkey 17 js::touint16 added in spidermonkey 17 js::toint32 added in spidermonkey 17 js::touint32 added in spidermonkey 17 js::toint64 added in spidermonkey 17 js::touint64 added in spidermonkey 17 js::tonumber added in spidermonkey 17 js::tostring added in spidermonkey 31 js::ordinarytoprimitive added in spidermonkey 38 js_valuetoconstructor js_valuetofunction js_valuetoobject js_valuetosource js_convertvalue js_valuetoboolean obsolete since jsapi 28 js_valuetoecmaint32 obsolete since jsapi 26 js_valuetoecmauint32 obsolete since jsapi 28 js_valuetoint32 obsolete since jsapi 28 js_valuetonumber obsolete since jsapi 27 js_valuetostring obsolete since jsapi 28 js_valuetouint16 obsolete since jsapi 28 fast, unchecked type-casting macros.
nsIDOMSerializer
to create an instance, use: var domserializer = components.classes["@mozilla.org/xmlextras/xmlserializer;1"] .createinstance(components.interfaces.nsidomserializer); method overview void serializetostream(in nsidomnode root, in nsioutputstream stream, in autf8string charset); astring serializetostring(in nsidomnode root); methods serializetostream() the subtree rooted by the specified element is serialized to a byte stream using the character set specified.
... serializetostring() the subtree rooted by the specified element is serialized to a string.
... astring serializetostring( in nsidomnode root ); parameters root the root of the subtree to be serialized.
nsIEditor
splitnode(in nsidomnode existingrightnode, in long offset, out nsidomnode newleftnode); void joinnodes(in nsidomnode leftnode, in nsidomnode rightnode, in nsidomnode parent); void deletenode(in nsidomnode child); void marknodedirty(in nsidomnode node); direction controller void switchtextdirection(); output methods astring outputtostring(in astring formattype, in unsigned long flags); example: // flags are declared in base/public/nsidocumentencoder.idl // outputselectiononly = 1, outputformatted = 2, // outputraw = 4, outputbodyonly = 8, // outputpreformatted = 16, outputwrap = 32, // outputformatflowed = 64, outputabsolutelinks = 258, // outputencodew3centities = 256, outputcrlin...
...ebreak = 512, // outputlflinebreak = 1024, outputnoscriptcontent = 2048, // outputnoframescontent = 4096, outputnoformattinginpre = 8192, // outputencodebasicentities=16384, outputencodelatin1entities=32768, // outputencodehtmlentities=65536, outputpersistnbsp=131072 editorapi.outputtostring('text/html', 2); editorapi.outputtostring('text/plain', 4); // output the body tag, body children and the html end tag (</html>).
...editorapi.outputtostring('text/html', 8); // xml: all in xml with _moz_dirty="" in new tags, html tags are in upper case // application/xhtml+xml format do the same editorapi.outputtostring('text/xml', 2); // the body is not recognized, everything is printed void outputtostream(in nsioutputstream astream, in astring formattype, in acstring charsetoverride, in unsigned long flags); listener methods void addeditorobserver(in nsieditorobserver observer);obsolete since gecko 18 void seteditorobserver(in editactionlistener observer); void removeeditorobserver(in nsieditorobserver observer obsolete since gecko 18); void addeditactionlistener(in nsieditactionlistener listener); void removeedita...
nsIException
inherits from: nsisupports last changed in gecko 1.7 method overview string tostring(); attributes attribute type description columnnumber pruint32 valid column numbers begin at 0.
... methods tostring() a generic formatter - make it suitable to print, etc.
... string tostring(); parameters none.
nsIJSID
method overview boolean equals(in nsijsid other); const nsid* getid(); violates the xpcom interface guidelines void initialize(in string idstring); string tostring(); attributes attribute type description id nsidptr read only.
... tostring() this methods returns a string representation of the object.
... string tostring(); parameters none.
nsIMsgIdentity
te(in string name, in astring value); acstring getcharattribute(in string name); void setcharattribute(in string name, in acstring value); boolean getboolattribute(in string name); void setboolattribute(in string name, in boolean value); long getintattribute(in string name); void setintattribute(in string name, in long value); astring tostring(); attributes attribute type description identityname astring fullname astring user's full name, i.e.
... tostring() converts the nsimsgidentity to a string.
... astring tostring(); ...
nsIPrefLocalizedString
inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void setdatawithlength(in unsigned long length, [size_is(length)] in wstring data); wstring tostring(); attributes attribute type description data wstring provides access to string data stored in this property.
... tostring() used to retrieve the contents of this object into a wide string.
...wstring tostring(); parameters none.
nsIScriptError
n wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category); void initwithwindowid(in wstring message, in wstring sourcename, in wstring sourceline, in pruint32 linenumber, in pruint32 columnnumber, in pruint32 flags, in string category, in unsigned long long innerwindowid); autf8string tostring(); attributes attribute type description category string a string indicating the category of error that occurred see categories for a list.
... tostring() outputs a string representing the error message described by the object.
... autf8string tostring(); parameters none.
nsISelection
nsidomrange getrangeat(in long index); void modify(in domstring alter, in domstring direction, in domstring granularity); void removeallranges(); void removerange(in nsidomrange range); void selectallchildren(in nsidomnode parentnode); void selectionlanguagechange(in boolean langrtl); domstring tostring(); attributes attribute type description anchornode nsidomnode returns the node in which the selection begins.
... tostring() returns the whole selection into a plain text string.
... domstring tostring(); remarks see also ...
nsIStackFrame
inherits from: nsisupports last changed in gecko 1.7 method overview string tostring(); attributes attribute type description caller nsistackframe read only.
... example to output the stack at a particular location: var s = components.stack; while(s) { console.log(s.name); s = s.caller; } methods tostring() a generic formatter - make it suitable to print, and so forth.
... string tostring(); parameters none.
nsISupportsCString
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data acstring provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsChar
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data char provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsDouble
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data double provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsFloat
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data float provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsID
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data nsidptr provides access to the native type represented by the object.
... methods tostring() this method returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsInterfacePointer
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data nsisupports provides access to the native type represented by the object.
... methods tostring() returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRBool
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data prbool provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRInt16
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data print16 provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRInt32
66 introduced gecko 1.0 inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data print32 provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRInt64
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data print64 provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRTime
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data prtime provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRUint16
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data pruint16 provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRUint32
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data pruint32 provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRUint64
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data pruint64 provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsPRUint8
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data pruint8 provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
nsISupportsString
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data astring provides access to the native type represented by the object.
... methods tostring() this methods returns a string valued representation of the object.
... string tostring(); parameters none.
ABI
method overview string tosource() string tostring() methods tosource() returns the string "ctypes.***_abi".
... tostring() returns a string identifying the abi.
... string tostring(); parameters none.
CType
method overview methods available on all ctype objects ctype array([n]) string tosource() string tostring() properties properties of all ctype objects these properties are available on all ctype objects.
... tostring() returns a string identifying the type.
... string tostring(); parameters none.
Int64
method overview number compare(a, b); number hi(a); int64 join(high, low); number lo(a); string tosource(); string tostring([radix]); methods compare() compares two 64-bit integer values.
... tostring() returns a string representation of the object's numeric value.
... string tostring( [radix] ); parameters radix optional the radix (base) to use when constructing the string.
UInt64
method overview number compare(a, b); number hi(a); uint64 join(high, low); number lo(a); string tosource(); string tostring([radix]); methods compare() compares two 64-bit integer values.
... tostring() returns a string representation of the object's numeric value.
... string tostring( [radix] ); parameters radix optional the radix (base) to use when constructing the string.
Using the CSS Typed Object Model - Web APIs
.x ); // cssunitvalue {value: 0.95, unit: "number"} console.log( transform[0].y ); // cssunitvalue {value: 0.95, unit: "number"} console.log( transform[0].z ); // cssunitvalue {value: 1, unit: "number"} console.log( transform.is2d ); // true // cssimagevalue let bgimage = allcomputedstyles.get('background-image'); console.log( bgimage ); // cssimagevalue console.log( bgimage.tostring() ); // url("https://mdn.mozillademos.org/files/16793/magicwand.png") // cssunparsedvalue let unit = allcomputedstyles.get('--unit'); console.log( unit ) // let parsedunit = cssnumericvalue.parse( unit ); console.log( parsedunit ); console.log( parsedunit.unit ); console.log( parsedunit.value ); for this example to work, the example must be closed out here.
... let bgimage = allcomputedstyles.get('background-image'); console.log( bgimage ); // cssimagevalue console.log( bgimage.tostring() ); // url("https://mdn.mozillademos.org/files/16793/magicwand.png") when we get() the 'background-image', a cssimagevalue is returned.
... while we used the css background shorthand property, the inherited object.prototype.tostring() method, shows we returned only the image, 'url("https://mdn.mozillademos.org/files/16793/magicwand.png")'.
DocumentOrShadowRoot.getSelection() - Web APIs
example function foo() { var selobj = document.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert()), the object's tostring() method is called and the returned value is passed to the function.
... in the above example, selobj.tostring() is automatically called when it is passed to window.alert().
...to use a selection object as a string, call its tostring() method directly: var selectedtext = selobj.tostring(); selobj is a selection object.
URLSearchParams.set() - Web APIs
params.set('baz', 3); params.tostring(); // "foo=1&bar=2&baz=3" below is a real-life example demonstrating how to create a url and set some search parameters.
... 'use strict' function genurl(rexp, atext, bdebug=false){ let theurl theurl= new url('https://regexr.com') theurl.searchparams.set( 'expression', rexp.tostring() ) theurl.searchparams.set( 'tool', 'replace' ) theurl.searchparams.set( 'input', '\u2911\u20dc' )// ⤑⃜ theurl.searchparams.set( 'text', atext.join('\n') ) if( bdebug ){ // display the key/value pairs for(var pair of theurl.searchparams.entries()) { console.debug(pair[0] + ' = \'' + pair[1] + '\''); } console.debug(theurl) } return theurl } var url = genurl( /(^\s*\/\/|\s*[...
...e-next-line no-unused-vars", "lockpref( 'keyword.url',\t\t'https://duckduckgo.com/html/?q=!+' )\t// test", "/*", " * bla bla ", "*/", "", "/* bla bla */", "", "// bla bla ", "", "these shouldn\'t work:", "console.log(\"http://foo.co.uk/\")", "var url = \"http://regexr.com/foo.html?q=bar\"", "alert(\"https://mediatemple.net\")", ] , true ) console.info( url, url.tostring() ) // window.open( url, 'regex_site' ) specifications specification status comment urlthe definition of 'set()' in that specification.
A re-introduction to JavaScript (JS tutorial) - JavaScript
method name description a.tostring() returns a string with the tostring() of each element separated by commas.
...the root of that chain is object.prototype, whose methods include tostring() — it is this method that is called when you try to represent an object as a string.
... this is useful for debugging our person objects: var s = new person('simon', 'willison'); s.tostring(); // [object object] person.prototype.tostring = function() { return '<person: ' + this.fullname() + '>'; } s.tostring(); // "<person: simon willison>" remember how avg.apply() had a null first argument?
Closures - JavaScript
consider the following case: function myobject(name, message) { this.name = name.tostring(); this.message = message.tostring(); this.getname = function() { return this.name; }; this.getmessage = function() { return this.message; }; } because the previous code does not take advantage of the benefits of using closures in this particular instance, we could instead rewrite it to avoid using closure as follows: function myobject(name, message) { this.name = name.tos...
...tring(); this.message = message.tostring(); } myobject.prototype = { getname: function() { return this.name; }, getmessage: function() { return this.message; } }; however, redefining the prototype is not recommended.
... the following example instead appends to the existing prototype: function myobject(name, message) { this.name = name.tostring(); this.message = message.tostring(); } myobject.prototype.getname = function() { return this.name; }; myobject.prototype.getmessage = function() { return this.message; }; in the two previous examples, the inherited prototype can be shared by all objects and the method definitions need not occur at every object creation.
Inheritance and the prototype chain - JavaScript
{ constructor: ƒ dosomething(), __proto__: { constructor: ƒ object(), hasownproperty: ƒ hasownproperty(), isprototypeof: ƒ isprototypeof(), propertyisenumerable: ƒ propertyisenumerable(), tolocalestring: ƒ tolocalestring(), tostring: ƒ tostring(), valueof: ƒ valueof() } } we can add properties to the prototype of dosomething(), as shown below.
...g(){} dosomething.prototype.foo = "bar"; console.log( dosomething.prototype ); this results in: { foo: "bar", constructor: ƒ dosomething(), __proto__: { constructor: ƒ object(), hasownproperty: ƒ hasownproperty(), isprototypeof: ƒ isprototypeof(), propertyisenumerable: ƒ propertyisenumerable(), tolocalestring: ƒ tolocalestring(), tostring: ƒ tostring(), valueof: ƒ valueof() } } we can now use the new operator to create an instance of dosomething() based on this prototype.
...r to the following: { prop: "some value", __proto__: { foo: "bar", constructor: ƒ dosomething(), __proto__: { constructor: ƒ object(), hasownproperty: ƒ hasownproperty(), isprototypeof: ƒ isprototypeof(), propertyisenumerable: ƒ propertyisenumerable(), tolocalestring: ƒ tolocalestring(), tostring: ƒ tostring(), valueof: ƒ valueof() } } } as seen above, the __proto__ of dosomeinstancing is dosomething.prototype.
Array.prototype.toLocaleString() - JavaScript
// tostring(?
...get(a, tostring(k)).
... // tostring(?
BigInt - JavaScript
bigint.prototype.tostring() returns a string representing the specified object in the specified radix (base).
... overrides the object.prototype.tostring() method.
...however, you can implement your own tojson method if needed: bigint.prototype.tojson = function() { return this.tostring() } instead of throwing, json.stringify now produces a string like this: json.stringify(bigint(1)) // '"1"' examples calculating primes // returns true if passed bigint is a prime number function isprime(p) { for (let i = 2n; i * i <= p; i++) { if (p % i === 0n) return false; } return true } // takes a bigint as an argument, returns nth prime number as bigint function nthprime(nt...
Date.prototype[@@toPrimitive] - JavaScript
if hint is "string" or "default", [@@toprimitive]() tries to call the tostring method.
... if the tostring property does not exist, it tries to call the valueof method and if the valueof does not exist either, [@@toprimitive]() throws a typeerror.
... if hint is "number", [@@toprimitive]() first tries to call valueof, and if that fails, it calls tostring.
Date.prototype.toDateString() - JavaScript
calling tostring() will return the date formatted in a human readable form in english.
... the todatestring() method is especially useful because compliant engines implementing ecma-262 may differ in the string obtained from tostring() for date objects, as the format is implementation-dependent and simple string slicing approaches may not produce consistent results across multiple engines.
... examples a basic usage of todatestring() var d = new date(1993, 5, 28, 14, 39, 7); console.log(d.tostring()); // logs mon jun 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.todatestring()); // logs mon jun 28 1993 note: month are 0-indexed when used as an argument of date (thus 0 corresponds to january and 11 to december).
Date.prototype.toTimeString() - JavaScript
calling tostring() will return the date formatted in a human readable form in american english.
... the totimestring() method is especially useful because compliant engines implementing ecma-262 may differ in the string obtained from tostring() for date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines.
... examples a basic usage of totimestring() var d = new date(1993, 6, 28, 14, 39, 7); console.log(d.tostring()); // wed jul 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.totimestring()); // 14:39:07 gmt-0600 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.totimestring' in that specification.
String - JavaScript
string.prototype.tostring() returns a string representing the specified object.
... overrides the object.prototype.tostring() method.
...tring.prototype.fontcolor() <font color="color"> string.prototype.fontsize() <font size="size"> string.prototype.italics() <i> string.prototype.link() <a href="url"> (link to url) string.prototype.small() <small> string.prototype.strike() <strike> string.prototype.sub() <sub> string.prototype.sup() <sup> examples string conversion it's possible to use string as a more reliable tostring() alternative, as it works when used on null, undefined, and on symbols.
parseFloat() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
... parsefloat will parse non-string objects if they have a tostring or valueof method.
... examples parsefloat returning a number the following examples all return 3.14: parsefloat(3.14); parsefloat('3.14'); parsefloat(' 3.14 '); parsefloat('314e-2'); parsefloat('0.0314e+2'); parsefloat('3.14some non-digit characters'); parsefloat({ tostring: function() { return "3.14" } }); parsefloat returning nan the following example returns nan: parsefloat('ff2'); parsefloat and bigint the following examples both return 900719925474099300, losing precision as the integer is too large to be represented as a float: parsefloat(900719925474099267n); parsefloat('900719925474099267n'); specifications specification ecmascript (ecma-262)the definition of 'parsefloat' in th...
Communicating using "port" - Archive of obsolete content
var pagemodscript = "window.addeventlistener('click', function(event) {" + " self.port.emit('click', event.target.tostring());" + " event.stoppropagation();" + " event.preventdefault();" + "}, false);" + "self.port.on('warning', function(message) {" + "window.alert(message);" + "});" var pagemod = require('sdk/page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: func...
... for example, to include an array of strings in the payload: var pagemodscript = "self.port.emit('loaded'," + " [" + " document.location.tostring()," + " document.title" + " ]" + ");" var pagemod = require('page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.port.on('loaded', function(pageinfo) { console.log(pageinfo[0]); console.log(pageinfo[1]); }); } }); ...
Private Properties - Archive of obsolete content
when an object is used as a key, it's converted to a string using its tostring method.
... to make the above code work, a unique identifier must be associated with each image and override its tostring method.
url - Archive of obsolete content
url methods tostring() returns a string representation of the url.
...for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.search); // ?example=true&visible=yes dataurl methods tostring() returns a string representation of the data url.
core/heritage - Archive of obsolete content
also you can mix inheritance and composition together if necessary: var point = class({ initialize: function initialize(x, y) { this.x = x; this.y = y; }, tostring: function tostring() { return this.x + ':' + this.y; } }) var pixel = class({ extends: point, implements: [ color ], initialize: function initialize(x, y, color) { color.prototype.initialize.call(this, color); point.prototype.initialize.call(this, x, y); }, tostring: function tostring() { return this.hex() + '@' + point.prototype.tostring.call(this) } }); var pixel...
... = pixel(11, 23, 'cc3399'); pixel.tostring(); // => #cc3399@11:23 pixel instanceof pixel // => true pixel instanceof point // => true extend module exports extend utility function, that is useful for creating objects that inherit from other objects, without associated classes.
Miscellaneous - Archive of obsolete content
utils = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindowutils); utils.sendmouseevent("mousedown", 10, 10, 0, 1, 0); utils.sendmouseevent("mouseup", 10, 10, 0, 1, 0); getting the currently selected text from browser.xul overlay context: var selectedtext = document.commanddispatcher.focusedwindow.getselection().tostring(); or: content.getselection(); // |window| object is implied; i.e., window.content.getselection() or: getbrowserselection(); // |window| object is implied; i.e., window.getbrowserselection() this final option massages the selection to remove leading and trailing whitespace.
...= cc["@mozilla.org/binaryinputstream;1"].createinstance(ci.nsibinaryinputstream); stream.setinputstream(postdata); var postbytes = stream.readbytearray(stream.available()); var poststr = string.fromcharcode.apply(null, postbytes); //do anything to your poststr alert(poststr); getting a string from the input stream is made somewhat simpler in firefox 4, by the addition of netutil.readinputstreamtostring() getting postdata of a request before the request is sent the above code will get the postdata for a page that has already loaded.
Tabs - Archive of obsolete content
ArchiveMozillaJetpackUITabs
blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded.
... urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded.
How to implement a custom XUL query processor component - Archive of obsolete content
here is our sample javascript xpcom query processor: components.utils.import("resource://gre/modules/xpcomutils.jsm"); // basic wrapper for nsixultemplateresult function templateresult(adata) { this._data = adata; // just make a random number for the id this._id = math.random(100000).tostring(); } templateresult.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsixultemplateresult]), // private storage _data: null, // right now our results are flat lists, so no containing/recursion take place iscontainer: false, isempty: true, mayprocesschildren: false, resource: null, type: "simple-item", get id() { return this._id; }, // ret...
...from the beginning of the name var name = avar.tostring().slice(1); return this._data[name]; }, // return an object instead of a string for convenient comparison purposes // or null to say just use string value getbindingobjectfor: function(avar) { return null; }, // called when a rule matches this item.
E4X for templating - Archive of obsolete content
security and escaping function e (str) { if (typeof str === 'xml') {str = str.tostring();} return str; } function quot (s) { // useful for placing user input within inline javascript; may be combined with escape function above as well if (typeof s === 'string') { return s.replace(/"/g, '&quot;').replace(/'/g, '&apos;'); } if (typeof s === 'xml') { return s.tostring().replace(/"/g, '&quot;').replace(/'/g, '&apos;'); } return string(s).replace...
...et = <></>; for (k in xmllist) { if (xmllist.hasownproperty(k)) { arr.push(xmllist[k]); } } arr.sort(h).foreach(function (item) { if (typeof item === 'xml') { ret += item; } else if (typeof item === 'string') { ret += new xml(item); } else { var ser = (new xmlserializer()).serializetostring(item); ret += new xml(ser); } }); return ret; } example: var fruits = <fruits> <item>pear</item> <item>banana</item> <item>grapes</item> </fruits>; alert( // using a javascript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.text() /* text() call may not be necessary */ )} </output>.toxmlstring() ); /* <output> <item>b...
Introduction - Archive of obsolete content
what really happens with the {} notation is that the variables' tostring method is called, and the returned value is placed in the element.
...serializing one of the most powerful tools of e4x is its ability to serialize an entire xml document (or portion thereof) into a string with one simple call to .toxmlstring() var element1 = <foo/>; var element2 = <bar/>; element1.appendchild(element2); element1.toxmlstring(); this will print <foo> <bar/> </foo> calling tostring() will achieve the same effect in this case, though calling tostring() on an element with only text content will product the text content (e.g., <foo>abc</foo>.tostring(); will simply provide 'abc').
ECMAScript 2015 support in Mozilla - Archive of obsolete content
.min_safe_integer (firefox 31) number.issafeinteger() (firefox 32) additions to the object object object.prototype.__proto__ has been standardized object.is() (firefox 22) object.setprototypeof() (firefox 31) object.assign() (firefox 34) object.getownpropertysymbols() (firefox 33) additions to the date object date.prototype is an ordinary object (firefox 41) generic date.prototype.tostring (firefox 41) date.prototype[@@toprimitive] (firefox 44) new promise object promise (firefox 24, enabled by default in firefox 29) new proxy object proxy (firefox 18) preventextensions() trap (firefox 22) isextensible() trap (firefox 31) getprototypeof() and setprototypeof() traps (firefox 49) new reflect object reflect (firefox 42) additions to the regexp object regexp sti...
...cky (y) flag (firefox 38) regexp unicode (u) flag (firefox 46) generic regexp.prototype.tostring (firefox 39) regexp.prototype[@@match]() (firefox 49) regexp.prototype[@@replace]() (firefox 49) regexp.prototype[@@search]() (firefox 49) regexp.prototype[@@split]() (firefox 49) get regexp[@@species] (firefox 49) additions to the string object string.fromcodepoint() (firefox 29) string.prototype.codepointat() (firefox 29) string.prototype.startswith(), string.prototype.endswith() (firefox 17) string.prototype.includes() (firefox 40) (formerly string.prototype.contains() (firefox 17)) string.prototype.repeat() (firefox 24) string.prototype.normalize() (firefox 31) string.raw() (firefox 34) \u{xxxxxx} unicode code point escapes (firefox 40) new symbol object symbol (firefox 36) ...
JavaArray - Archive of obsolete content
in addition, the tostring method is inherited from the object object and returns the following value: [object javaarray] you must specify a class object, such as one returned by java.lang.object.forname, for the componenttype parameter of newinstance when you use this method to create an array.
... methods tostring: in javascript 1.4, this method is overridden by the inherited method java.lang.object.tostring.
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
if you really want to show a symbol, we need to call .tostring() on it.
... let sym = symbol("sym") alert(sym.tostring()) // symbol(sym), now it works or you can use the symbol.description property to get its description: let _sym = symbol("sym"); alert(_sym.description); // sym well-known symbols the symbol class has constants for so-called well-known symbols.
Handling text — strings in JavaScript - Learn web development
try the following: let mystring = '123'; let mynum = number(mystring); typeof mynum; conversely, every number has a method called tostring() that converts it to the equivalent string.
... try this: let mynum = 123; let mystring = mynum.tostring(); typeof mystring; these constructs can be really useful in some situations.
Object prototypes - Learn web development
you will however also see some other members — tostring, valueof, etc — these are defined on person1's prototype object's prototype object, which is object.prototype.
... so object.prototype.tostring(), object.prototype.valueof(), etc., are available to any object types that inherit from object.prototype, including new object instances created from the person() constructor.
JS::OrdinaryToPrimitive
most users should not call this -- use js::tonumber, js::toboolean, or js::tostring instead.
... see also mxr id search for js::ordinarytoprimitive js::tonumber js::toboolean js::tostring bug 1103152 ...
JS::Value
lean() val.setboolean(bool) number val.isint32(), val.isdouble(), val.isnumber() js::numbervalue(any number type), js::int32value(int32_t), js::doublevalue(double), js::float32value(float) val.toint32(), val.todouble(), val.tonumber() val.setint32(int32_t), val.setnumber(uint32_t), val.setnumber(double) string val.isstring() js::stringvalue(jsstring*) val.tostring() val.setstring(jsstring *) object val.isobject() js::objectvalue(jsobject&amp;), js::objectornullvalue(jsobject*) val.toobject() val.setobject(jsobject &) symbol val.issymbol() js::symbolvalue(js::symbol*) val.tosymbol() val.setsymbol(js::symbol &) numbers are stored in a js::value either as a double or as an int32_t.
... js::value is not inherently type-safe it is an error to call any accessor method on a value of a non-matching type: val.toint32() must only be called if val.isint32(), val.tostring() must only be called if val.isstring(), and so on.
JSAutoByteString
examples use constructor arguments { jsstring *str = js::tostring(cx, strval); if (!str) return false; jsautobytestring bytes(cx, str); /* calls js_encodestring internally */ if (!bytes) return false; /* ...do something with bytes...
...*/ } use method to encode string { js::rootedstring str(cx, js::tostring(cx, strval)); if (!str) return false; jsautobytestring bytes; if (!bytes.encodeutf8(cx, str)) /* calls js_encodestringtoutf8 internally */ return false; /* ...do something with bytes...
JSObjectOps.defaultValue
it calls the javascript methods obj.valueof() and/or obj.tostring().
... js_convertstub implements the default behavior for the jsclass.convert hook, which is to call obj.valueof() and obj.tostring() in accordance with the algorithm in es5 §8.12.8.
Places Developer Guide
getservice(components.interfaces.nspiplacesdatabase).dbconnection; } and then to get the a redirected visit_id from another visit_id: function getfromvisit(visit_id) { var sql = <cdata><![cdata[ select from_visit from moz_places, moz_historyvisits where moz_historyvisits.id = :visit_id and moz_places.id = moz_historyvisits.place_id; ]]></cdata>.tostring(); var sql_stmt = getplacesdbconn.createstatement(sql); sql_stmt.params.visit_id = visit_id; var from_visit; try { // here we can't use the "executeasync" method since have to return a // result right-away.
... while (sql_stmt.executestep()) { from_visit = sql_stmt.row.from_visit; } } finally { sql_stmt.reset(); } return from_visit; } note: the <cdata><![cdata[ xxx ]]></cdata>.tostring() notation is e4x and it makes possible to write multi-line strings in javascript.
Components.Constructor
for example: var binaryinputstream = components.constructor("@mozilla.org/binaryinputstream;1"); var bis = new binaryinputstream(); print(bis.tostring()); // "[xpconnect wrapped nsisupports]" try { // someinputstream is an existing nsiinputstream // throws because bis hasn't been qi'd to nsibinaryinputstream bis.setinputstream(someinputstream); } catch (e) { bis.queryinterface(components.interfaces.nsibinaryinputstream); bis.setinputstream(someinputstream); // succeeds now } if two arguments are given, the created instance will be ...
...nsisupports.queryinterface()'d to the xpcom interface whose name is the second argument: var binaryinputstream = components.constructor("@mozilla.org/binaryinputstream;1", "nsibinaryinputstream"); var bis = new binaryinputstream(); print(bis.tostring()); // "[xpconnect wrapped nsibinaryinputstream]" // someinputstream is an existing nsiinputstream bis.setinputstream(someinputstream); // succeeds if three arguments are given, then in addition to being nsisupports.queryinterface()'d, the instance will also have had an initialization method called on it.
NS_ConvertASCIItoUTF16
(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsautostring data members no public members.
... methods constructors void ns_convertasciitoutf16(const char*) - source parameters char* acstring void ns_convertasciitoutf16(const char*, pruint32) - source parameters char* acstring pruint32 alength void ns_convertasciitoutf16(const nsacstring_internal&) - source parameters nsacstring_internal& acstring operator= nsautostring& operator=(const nsautostring&) - source parameters nsautostring& str nsstring& operator=(const nsstring&) - source parameters nsstring& str nsastring_internal& operator=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& op...
NS_ConvertUTF16toUTF8
const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscautostring data members no public members.
...structors void ns_convertutf16toutf8(const prunichar*) - source a helper class that converts a utf-16 string to utf-8 parameters prunichar* astring void ns_convertutf16toutf8(const prunichar*, pruint32) - source parameters prunichar* astring pruint32 alength void ns_convertutf16toutf8(const nsastring_internal&) - source parameters nsastring_internal& astring operator= nscautostring& operator=(const nscautostring&) - source parameters nscautostring& str nscstring& operator=(const nscstring&) - source parameters nscstring& str nsacstring_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstri...
NS_ConvertUTF8toUTF16
(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nsautostring data members no public members.
... methods constructors void ns_convertutf8toutf16(const char*) - source parameters char* acstring void ns_convertutf8toutf16(const char*, pruint32) - source parameters char* acstring pruint32 alength void ns_convertutf8toutf16(const nsacstring_internal&) - source parameters nsacstring_internal& acstring operator= nsautostring& operator=(const nsautostring&) - source parameters nsautostring& str nsstring& operator=(const nsstring&) - source parameters nsstring& str nsastring_internal& operator=(prunichar) - source parameters prunichar c nsastring_internal& operator=(const prunichar*) - source parameters prunichar* data nsastring_internal& operator=(const nsastring_internal&) - source parameters nsastring_internal& str nsastring_internal& opera...
NS_LossyConvertUTF16toASCII
const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(const char appendliteral(char operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscautostring data members no public members.
...6toascii(const prunichar*) - source a helper class that converts a utf-16 string to ascii in a lossy manner parameters prunichar* astring void ns_lossyconvertutf16toascii(const prunichar*, pruint32) - source parameters prunichar* astring pruint32 alength void ns_lossyconvertutf16toascii(const nsastring_internal&) - source parameters nsastring_internal& astring operator= nscautostring& operator=(const nscautostring&) - source parameters nscautostring& str nscstring& operator=(const nscstring&) - source parameters nscstring& str nsacstring_internal& operator=(char) - source parameters char c nsacstring_internal& operator=(const char*) - source parameters char* data nsacstring_internal& operator=(const nsacstring_internal&) - source parameters nsacstri...
nsICategoryManager
ponents.classes["@mozilla.org/categorymanager;1"] .getservice(components.interfaces.nsicategorymanager); var enumerator = categorymanager.enumeratecategories(); var categories = []; while (enumerator.hasmoreelements()) { var item = enumerator.getnext(); var category = item.queryinterface(components.interfaces.nsisupportscstring) categories.push(category.tostring()); } categories.sort(); var categoriesstring = categories.join("\n"); dump(categoriesstring + "\n"); print out a list of app-startup entries this example prints out a list of entries of "app-startup" category.
...mponents.classes["@mozilla.org/categorymanager;1"] .getservice(components.interfaces.nsicategorymanager); var enumerator = categorymanager.enumeratecategory("app-startup"); var entries = []; while (enumerator.hasmoreelements()) { var item = enumerator.getnext(); var entry = item.queryinterface(components.interfaces.nsisupportscstring) entries.push(entry.tostring()); } entries.sort(); var entriesstring = entries.join("\n"); dump(entriesstring + "\n"); disable currently loaded plugins by type this snippet here shows how to disable plugins that are currently loaded for the file type of pdf.
nsICryptoHash
erfaces.nsicryptohash); // we want to use the sha256 algorithm ch.init(ch.sha256); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } // convert the binary hash data to a hex string.
...a is an array of bytes var data = converter.converttobytearray(str, result); var ch = components.classes["@mozilla.org/security/hash;1"] .createinstance(components.interfaces.nsicryptohash); ch.init(ch.sha256); ch.update(data, data.length); var hash = ch.finish(false); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } // convert the binary hash data to a hex string.
nsIHttpChannelInternal
localaddress autf8string the local ip address to which the channel is bound, in the same format produced by pr_netaddrtostring().
... obsolete since gecko 1.9 remoteaddress autf8string the ip address of the remote host to which this channel is bound, in the same format produced by pr_netaddrtostring().
nsIMsgIncomingServer
ue(in string relpref, in string abspref, in nsilocalfile avalue); void setfilterlist(in nsimsgfilterlist afilterlist); void setintattribute(in string name, in long value); void setintvalue(in string attr, in long value); void setunicharattribute(in string name, in astring value); void setunicharvalue(in string attr, in astring value); void shutdown(); void storepassword(); astring tostring(); void writetofoldercache(in nsimsgfoldercache foldercache); attributes attribute type description accountmanagerchrome astring read only.
...exceptions thrown missing exception missing description tostring() astring tostring(); parameters none.
nsISelectionPrivate
void startbatchchanges(); wstring tostringwithformat(in string formattype, in unsigned long flags, in print32 wrapcolumn); attributes attribute type description cancacheframeoffset boolean frame offset cache can be used just during calling nseditor::endplaceholdertransaction.
... tostringwithformat() wstring tostringwithformat( in string formattype, in unsigned long flags, in print32 wrapcolumn ); parameters formattype flags wrapcolumn return value ...
nsISupportsVoid
inherits from: nsisupportsprimitive last changed in gecko 1.0 method overview string tostring(); attributes attribute type description data voidptr this attribute provides access to the native type represented by the object.
... methods tostring() string tostring(); parameters none.
nsIXmlRpcFault
inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void init(in print32 faultcode, in string faultsring); string tostring(); attributes attribute type description faultcode print32 read only.
... methods init() void getdata( in print32 faultcode, in string faultstring ); parameters faultcode tostring() string tostring(); ...
Standard OS Libraries
gdkwindow.ptr, // window gint.ptr, // x gint.ptr, // y gdkmodifiertype.ptr // mask ); var winroot_gdkwindowptr = gdk_get_default_root_window(); console.info('winroot_gdkwindowptr:', winroot_gdkwindowptr, winroot_gdkwindowptr.tostring()); // gdk2 var x = gint(); var y = gint(); var mask = gdkmodifiertype(); var win_undermouse = gdk_window_get_pointer( winroot_gdkwindowptr, x.address(), y.address(), mask.address() ); console.info('win_undermouse:', win_undermouse, win_undermouse.tostring()); console.info('x:', x, x.tostring()); console.info('y:', y, y.tostring()); console.info('mask:', mask, mask.tostring()); ...
...ptr = gdk_display_get_device_manager(displayptr); var deviceptr = gdk_device_manager_get_client_pointer(device_managerptr); var x = gint(); var y = gint(); var mask = gdkmodifiertype(); var win_undermouse = gdk_window_get_device_position( winroot_gdkwindowptr, deviceptr, x.address(), y.address(), mask.address() ); console.info('win_undermouse:', win_undermouse, win_undermouse.tostring()); console.info('x:', x, x.tostring()); console.info('y:', y, y.tostring()); console.info('mask:', mask, mask.tostring()); gdk.close(); gdk3.close(); gtk+ the gtk+ toolkit can also be used.
Working with ArrayBuffers
pixelbuffer.tostring(); // "ctypes.uint8_t.ptr(ctypes.uint64("0x352e0000"))" var imgwidth = 400; var imgheight = 400; var myimgdat = new imagedata(imgwidth, imgheight); method 1: passing arraytype cdata to uint8clampedarray.prototype.set one method is to get into a js-ctypes array, and then set it into the imagedata, as illustrated by the following code example.
...var casted = ctypes.cast(pixelbuffer.address(), ctypes.uint8_t.array(myimgdata.data.length).ptr).contents; // myimgdat.data.length is imgwidth * imgheight * 4 because per pixel there is r, g, b, a numbers casted.tostring(); // "ctypes.uint8_t.array(640000)([45, 66, 135, 255, 99, 86, 55, 255, ..........
ArrayType
method overview methods inherited from ctype ctype array([n]) string tosource() string tostring() arraytype cdata syntax cdata sized_arraytype(); cdata unsized_arraytype(length); sized_arraytype and unsized_arraytype are arraytype ctype.
... arraytype cdata method_overview cdata addressofelement(idx) methods inherited from cdata cdata address() string tosource() string tostring() arraytype cdata methods addressofelement() returns a new cdata object of the appropriate pointer type, whose value points to the specified array element on which the method was called.
PointerType
method overview methods inherited from ctype ctype array([n]) string tosource() string tostring() pointertype cdata syntax cdata pointertype(); pointertype is pointertype ctype.
... pointertype cdata method_overview bool isnull() methods inherited from cdata cdata address() string tosource() string tostring() pointertype cdata methods isnull() determines whether or not the pointer's value is null.
StructType
method overview define(fields) methods inherited from ctype ctype array([n]) string tosource() string tostring() methods define() defines a previously declared opaque type's fields.
... structtype cdata method_overview cdata addressoffield(name) methods inherited from cdata cdata address() string tosource() string tostring() structtype cdata methods addressoffield() returns a new cdata object of the appropriate pointer type, whose value points to the specified field of the structure on which the method was called.
Background Tasks API - Web APIs
function logtaskhandler(data) { log("<strong>running task #" + currenttasknumber + "</strong>"); for (i=0; i<data.count; i+=1) { log((i+1).tostring() + ".
... min = math.ceil(min); max = math.floor(max); return math.floor(math.random() * (max - min + 1)) + min; } function decodetechnostuff() { totaltaskcount = 0; currenttasknumber = 0; updatedisplay(); let n = getrandomintinclusive(100, 200); for (i=0; i<n; i++) { let taskdata = { count: getrandomintinclusive(75, 150), text: "this text is from task number " + (i+1).tostring() + " of " + n }; enqueuetask(logtaskhandler, taskdata); } } document.getelementbyid("startbutton").addeventlistener("click", decodetechnostuff, false); decodetechnostuff() starts by zeroing the values of totaltaskcount (the number of tasks added to the queue so far) and currenttasknumber (the task currently being run), and then calls updatedisplay() to reset the display to its "noth...
Using the CSS Painting API - Web APIs
paint(ctx, size, props, args) { // use our custom arguments const hasstroke = args[0].tostring(); // if stroke arg is 'stroke', don't fill if (hasstroke === 'stroke') { ctx.fillstyle = 'transparent'; ctx.strokestyle = colour; } ...
...the element // args -> list of arguments set when calling the paint() function in the css // where to start the highlight & dimensions const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; // the values passed in the paint() function in the css const colour = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strokewidth = parseint(args[1]); // set the stroke width if ( strokewidth ) { ctx.linewidth = strokewidth; } else { ctx.linewidth = 1.0; } // set the fill type if ( stroketype === 'stroke' ) { ctx.fillstyle = 'transparent'; ctx.strokestyle = colour; } else if ( stroketype === 'filled' ) { ctx.fillstyle = colour; ctx.strokestyle = colour; } else { ...
Selection - Web APIs
WebAPISelection
selection.tostring() returns a string currently being represented by the selection object, i.e.
... notes string representation of a selection calling the selection.tostring() method returns the text contained within the selection, e.g.: var selobj = window.getselection(); window.alert(selobj); note that using a selection object as the argument to window.alert will call the object's tostring method.
Selection API - Web APIs
once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using selection.tostring(), adding a range (as represented by a standard range object) to the selection (or removing one) with selection.addrange()/selection.removerange(), or changing the selection to be the entire contents of a dom node using selection.selectallchildren().
... yeschrome android full support yesfirefox android full support 55opera android full support yessafari ios full support yessamsung internet android full support yestostring experimentalchrome full support 1edge full support ≤18firefox full support yesie ?
TextEncoder - Web APIs
= (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/); resarr[respos += 1] = (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/); } } if (typeof uint8array !== "undefined") return resarr.subarray(0, respos + 1); // else // ie 6-9 resarr.length = respos + 1; // trim off extra weight return resarr; }; textencoder.prototype.tostring = function(){return "[object textencoder]"}; try { // object.defineproperty only works on dom prototypes in ie8 object.defineproperty(textencoder.prototype,"encoding",{ get:function(){if(textencoder.prototype.isprototypeof(this)) return"utf-8"; else throw typeerror("illegal invocation");} }); } catch(e) { /*ie6-8 fallback*/ textencode...
...r.prototype.encoding = "utf-8"; } if(typeof symbol!=="undefined")textencoder.prototype[symbol.tostringtag]="textencoder"; } source: https://github.com/anonyco/fastestsmallesttextencoderdecoder specifications specification status comment encodingthe definition of 'textencoder' in that specification.
URL.toJSON() - Web APIs
WebAPIURLtoJSON
the tojson() method of the url interface returns a usvstring containing a serialized version of the url, although in practice it seems to have the same effect as url.tostring().
... examples const url = new url("/docs/web/api/url/tostring"); url.tojson(); // should return the url as a string specifications specification status comment urlthe definition of 'tojson()' in that specification.
URL - Web APIs
WebAPIURL
methods tostring() returns a usvstring containing the whole url.
... to get the search params from the current window's url, you can do this: // https://some.site/?id=123 const parsedurl = new url(window.location.href); console.log(parsedurl.searchparams.get("id")); // "123" the tostring() method of url just returns the value of the href property, so the constructor can be used to normalize and encode a url directly.
URLSearchParams - Web APIs
urlsearchparams.tostring() returns a string containing a query string suitable for use in a url.
...for (let p of searchparams) { console.log(p); } searchparams.has("topic") === true; // true searchparams.get("topic") === "api"; // true searchparams.getall("topic"); // ["api"] searchparams.get("foo") === null; // true searchparams.append("topic", "webdev"); searchparams.tostring(); // "q=urlutils.searchparams&topic=api&topic=webdev" searchparams.set("topic", "more webdev"); searchparams.tostring(); // "q=urlutils.searchparams&topic=more+webdev" searchparams.delete("topic"); searchparams.tostring(); // "q=urlutils.searchparams" gotchas the urlsearchparams constructor does not parse full urls.
URLUtilsReadOnly - Web APIs
urlutilsreadonly.tostring() returns a domstring containing the whole url.
... nochrome android no support nofirefox android full support 4opera android no support nosafari ios no support nosamsung internet android no support notostring experimentalchrome no support noedge no support nofirefox full support 3.5ie no support noopera no support nosafari no support no...
DOM onevent handlers - Developer guides
let logelement = document.queryselector('div'); let el = document.queryselector("a"); function log(msg) { logelement.innerhtml += `${msg}<br>` }; function anchoronclick(event) { log("changed onclick handler") }; // original handler log(`element's onclick as a javascript property: <code> ${el.onclick.tostring()} </code>`); //changing handler using .onclick log('<br>changing onclick handler using <strong> onclick property </strong> '); el.onclick = anchoronclick; log(`changed the property to: <code> ${el.onclick.tostring()} </code>`); log(`but the html attribute is unchanged: <code> ${el.getattribute("onclick")} </code><br>`); //changing handler using .setattribute log('<hr/><br> changing onclick h...
...andler using <strong> setattribute method </strong> '); el.setattribute("onclick", 'anchoronclick(event)'); log(`changed the property to: <code> ${el.onclick.tostring()} </code>`); log(`now even the html attribute has changed: <code> ${el.getattribute("onclick")} </code><br>`); result for historical reasons, some attributes/properties on the <body> and <frameset> elements instead set event handlers on their parent window object.
Parsing and serializing XML - Developer guides
serializing an xml document given a document, you can serialize the document's dom tree back into xml using the xmlserializer.serializetostring() method.
... to serialize the dom tree doc into xml text, call xmlserializer.serializetostring(): var oserializer = new xmlserializer(); var sxml = oserializer.serializetostring(doc); serializing html documents if the dom you have is an html document, you can serialize using serializetostring(), but there is a simpler option: just use the element.innerhtml property (if you want just the descendants of the specified node) or the element.outerhtml property if you want the node and all its descendants.
Control flow and error handling - JavaScript
the following code throws several exceptions of varying types: throw 'error2'; // string type throw 42; // number type throw true; // boolean type throw {tostring: function() { return "i'm an object!"; } }; note: you can specify an object when you throw an exception.
... // create an object type userexception function userexception(message) { this.message = message; this.name = 'userexception'; } // make the exception convert to a pretty string when used as a string // (e.g., by the error console) userexception.prototype.tostring = function() { return `${this.name}: "${this.message}"`; } // create an instance of the object type and throw it throw new userexception('value too high'); try...catch statement the try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown.
Functions - JavaScript
for example: var y = function x() {}; alert(x); // throws an error the function name also appears when the function is serialized via function's tostring method.
... // this function returns a string padded with leading zeros function padzeros(num, totallen) { var numstr = num.tostring(); // initialize return value as string var numzeros = totallen - numstr.length; // calculate no.
Array.prototype.every() - JavaScript
if (typeof callbackfn !== 'function' && object.prototype.tostring.call(callbackfn) !== '[object function]') { throw new typeerror(); } // 5.
...let pk be tostring(k).
Array.prototype.indexOf() - JavaScript
let pk be tostring(k).
... let elementk be the result of calling the get // internal method of o with the argument tostring(k).
BigInt64Array - JavaScript
bigint64array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
BigUint64Array - JavaScript
biguint64array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Boolean - JavaScript
instance methods boolean.prototype.tostring() returns a string of either true or false depending upon the value of the object.
... overrides the object.prototype.tostring() method.
Date - JavaScript
date.prototype.tostring() returns a string representing the specified date object.
... overrides the object.prototype.tostring() method.
Error.prototype.name - JavaScript
the name property, in addition to the message property, is used by the error.prototype.tostring() method to create a string representation of the error.
... examples throwing a custom error var e = new error('malformed input'); // e.name is 'error' e.name = 'parseerror'; throw e; // e.tostring() would return 'parseerror: malformed input' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.name' in that specification.
Error - JavaScript
instance methods error.prototype.tostring() returns a string representing the specified object.
... overrides the object.prototype.tostring() method.
Float32Array - JavaScript
float32array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Float64Array - JavaScript
float64array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Function - JavaScript
function.prototype.tostring() returns a string representing the source code of the function.
... overrides the object.prototype.tostring method.
Int16Array - JavaScript
int16array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Int32Array - JavaScript
int32array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Int8Array - JavaScript
int8array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Intl.Locale.prototype.maximize() - JavaScript
examples using maximize let mylocale = new intl.locale("fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr" console.log(mylocale.tostring()); // prints "fr-u-ca-gregory-hc-h24" let mylocmaximized = mylocale.maximize(); // prints "fr-latn-fr".
...console.log(mylocmaximized.tostring()); specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.minimize() - JavaScript
examples using minimize let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-gregory-hc-h24" let mylocminimized = mylocale.minimize(); // prints "fr", since french is only written in the latin script // and is most likely to be spoken in france.
...console.log(mylocminimized.tostring()); specifications specification ecmascript internationalization api (ecma-402) ...
Math.ceil() - JavaScript
if (isnan(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return nan; } // shift value = value.tostring().split('e'); value = math[type](+(value[0] + 'e' + (value[1] ?
... (+value[1] - exp) : -exp))); // shift back value = value.tostring().split('e'); return +(value[0] + 'e' + (value[1] ?
Math.floor() - JavaScript
if (isnan(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return nan; } // shift value = value.tostring().split('e'); value = math[type](+(value[0] + 'e' + (value[1] ?
... (+value[1] - exp) : -exp))); // shift back value = value.tostring().split('e'); return +(value[0] + 'e' + (value[1] ?
Number - JavaScript
number.prototype.tostring([radix]) returns a string representing the specified object in the specified radix ("base").
... overrides the object.prototype.tostring() method.
Object.prototype.hasOwnProperty() - JavaScript
inherited properties the following example differentiates between direct properties and properties inherited through the prototype chain: o = new object(); o.prop = 'exists'; o.hasownproperty('prop'); // returns true o.hasownproperty('tostring'); // returns false o.hasownproperty('hasownproperty'); // returns false iterating over the properties of an object the following example shows how to iterate over the properties of an object without executing on inherited properties.
...value: ' + buz[name]); } else { console.log(name); // tostring or something else } } using hasownproperty as a property name javascript does not protect the property name hasownproperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasownproperty to get correct results: var foo = { hasownproperty: function() { return false; }, bar: 'here be dragons' }; foo.hasownprope...
Object.prototype.valueOf() - JavaScript
an object's valueof method is usually invoked by javascript, but you can invoke it yourself as follows: mynumbertype.valueof() note: objects in string contexts convert via the tostring() method, which is different from string objects converting to string primitives using valueof.
...custom types function mynumbertype(n) { this.number = n; } mynumbertype.prototype.valueof = function() { return this.number; }; var myobj = new mynumbertype(4); myobj + 3; // 7 using unary plus +"5" // 5 (string to number) +"" // 0 (string to number) +"1 + 2" // nan (doesn't evaluate) +new date() // same as (new date()).gettime() +"foo" // nan (string to number) +{} // nan +[] // 0 (tostring() returns an empty string list) +[1] // 1 +[1,2] // nan +new set([1]) // nan +bigint(1) // uncaught typeerror: cannot convert a bigint value to a number +undefined // nan +null // 0 +true // 1 +false // 0 specifications specification ecmascript (ecma-262)the definition of 'object.prototype.valueof' in that specification.
Object - JavaScript
object.prototype.tolocalestring() calls tostring().
... object.prototype.tostring() returns a string representation of the object.
RegExp - JavaScript
regexp.prototype.tostring() returns a string representing the specified object.
... overrides the object.prototype.tostring() method.
Symbol.prototype.description - JavaScript
it is different to symbol.prototype.tostring() as it does not contain the enclosing "symbol()" string.
... examples using description symbol('desc').tostring(); // "symbol(desc)" symbol('desc').description; // "desc" symbol('').description; // "" symbol().description; // undefined // well-known symbols symbol.iterator.tostring(); // "symbol(symbol.iterator)" symbol.iterator.description; // "symbol.iterator" // global symbols symbol.for('foo').tostring(); // "symbol(foo)" symbol.for('foo').description; // "foo" specifications specification ecmascript (ecma-262)the definition of 'get symbol.prototype.description' in that specification.
TypedArray - JavaScript
typedarray.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Uint16Array - JavaScript
uint16array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Uint32Array - JavaScript
uint32array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Uint8Array - JavaScript
uint8array.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
Uint8ClampedArray - JavaScript
uint8clampedarray.prototype.tostring() returns a string representing the array and its elements.
... see also array.prototype.tostring().
encodeURIComponent() - JavaScript
to be more stringent in adhering to rfc 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized uri delimiting uses, the following can be safely used: function fixedencodeuricomponent(str) { return encodeuricomponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charcodeat(0).tostring(16); }); } examples encoding for content-disposition and link headers the following example provides the special encoding required within utf-8 content-disposition and link server response header parameters (e.g., utf-8 filenames): var filename = 'my file(2).txt'; var header = "content-disposition: attachment; filename*=utf-8''" + encoderfc5987valuechars(filename); console.lo...
... // note that although rfc3986 reserves "!", rfc5987 does not, // so we do not need to escape it replace(/['()*]/g, c => "%" + c.charcodeat(0).tostring(16)).
eval() - JavaScript
eval(new string('2 + 2')); // returns a string object containing "2 + 2" eval('2 + 2'); // returns 4 you can work around this limitation in a generic fashion by using tostring().
... var expression = new string('2 + 2'); eval(expression.tostring()); // returns 4 if you use the eval function indirectly, by invoking it via a reference other than eval, as of ecmascript 5 it works in the global scope rather than the local scope.
parseInt() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
... to convert a number to its string literal in a particular radix, use thatnumber.tostring(radix).
Equality (==) - JavaScript
if one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueof() and tostring() methods.
...string2 = string("hello"); const string3 = new string("hello"); const string4 = new string("hello"); console.log(string1 == string2); // true console.log(string1 == string3); // true console.log(string2 == string3); // true console.log(string3 == string4); // false console.log(string4 == string4); // true comparing dates and strings const d = new date('december 17, 1995 03:24:00'); const s = d.tostring(); // for example: "sun dec 17 1995 03:24:00 gmt-0800 (pacific standard time)" console.log(d == s); //true specifications specification ecmascript (ecma-262)the definition of 'equality operators' in that specification.
typeof - JavaScript
nnot be type coerced to a number typeof 42n === 'bigint'; // strings typeof '' === 'string'; typeof 'bla' === 'string'; typeof `template literal` === 'string'; typeof '1' === 'string'; // note that a number within a string is still typeof string typeof (typeof 1) === 'string'; // typeof always returns a string typeof string(1) === 'string'; // string converts anything into a string, safer than tostring // booleans typeof true === 'boolean'; typeof false === 'boolean'; typeof boolean(1) === 'boolean'; // boolean() will convert values based on if they're truthy or falsy typeof !!(1) === 'boolean'; // two calls of the !
... (logical not) operator are equivalent to boolean() // symbols typeof symbol() === 'symbol' typeof symbol('foo') === 'symbol' typeof symbol.iterator === 'symbol' // undefined typeof undefined === 'undefined'; typeof declaredbutundefinedvariable === 'undefined'; typeof undeclaredvariable === 'undefined'; // objects typeof {a: 1} === 'object'; // use array.isarray or object.prototype.tostring.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof new date() === 'object'; typeof /regex/ === 'object'; // see regular expressions section for historical results // the following are confusing, dangerous, and wasteful.
Exported WebAssembly functions - WebAssembly
testfunc.tostring() returns an interesting result: function 0() { [native code] } this gives you more of an idea of its wrapper-type nature.
... their name property is the tostring() result of the function's index in the wasm module.
Reddit Example - Archive of obsolete content
event.stoppropagation(); event.preventdefault(); self.port.emit('click', t.tostring()); }); this script uses jquery to interact with the dom of the page and the self.port.emit function to pass urls back to the add-on script.
port - Archive of obsolete content
ire("sdk/self"); var pagemod = pagemods.pagemod({ include: ['*'], contentscriptfile: self.data.url("content-script.js"), onattach: setuplistener }); function setuplistener(worker) { worker.port.on('loaded', function(pageinfo) { console.log(pageinfo[0]); console.log(pageinfo[1]); }); } //content-script.js self.port.emit('loaded', [ document.location.tostring(), document.title ]); ...
Content Scripts - Archive of obsolete content
var pagemod = pagemods.pagemod({ include: ['*'], contentscriptfile: self.data.url("content-script.js"), onattach: startlistening }); function startlistening(worker) { worker.port.on('click', function(html) { worker.port.emit('warning', 'do not click this again'); }); } // content-script.js window.addeventlistener('click', function(event) { self.port.emit('click', event.target.tostring()); event.stoppropagation(); event.preventdefault(); }, false); self.port.on('warning', function(message) { window.alert(message); }); in the add-on above there are two messages: click is sent from the page-mod to the add-on, when the user clicks an element in the page warning sends a silly string back to the page-mod from tab.attach() the tab.attach() method returns the worker yo...
panel - Archive of obsolete content
var myscript = "window.addeventlistener('click', function(event) {" + " var t = event.target;" + " if (t.nodename == 'a')" + " self.port.emit('click-link', t.tostring());" + "}, false);" var mypanel = require("sdk/panel").panel({ contenturl: "http://www.bbc.co.uk/mobile/index.html", contentscript: myscript }); mypanel.port.on("click-link", function(url) { console.log(url); }); mypanel.show(); this example uses contentscript to supply the script as a string.
Creating annotations - Archive of obsolete content
} resetmatchedelement(); ancestor = $(this).closest("[id]"); matchedelement = $(this).first(); originalbgcolor = $(matchedelement).css('background-color'); $(matchedelement).css('background-color', 'yellow'); $(matchedelement).bind('click.annotator', function(event) { event.stoppropagation(); event.preventdefault(); self.port.emit('show', [ document.location.tostring(), $(ancestor).attr("id"), $(matchedelement).text() ] ); }); }); conversely, the add-on resets the matched element on mouseout: $('*').mouseout(function() { resetmatchedelement(); }); save this code in a new file called selector.js in your add-on's data directory.
Displaying annotations - Archive of obsolete content
the complete content script is here: self.on('message', function onmessage(annotations) { annotations.foreach( function(annotation) { if(annotation.url == document.location.tostring()) { createanchor(annotation); } }); $('.annotated').css('border', 'solid 3px yellow'); $('.annotated').bind('mouseenter', function(event) { self.port.emit('show', $(this).attr('annotation')); event.stoppropagation(); event.preventdefault(); }); $('.annotated').bind('mouseleave', function() { self.port.emit('hide'); }); }); function createanchor(annot...
Bookmarks - Archive of obsolete content
earlier creating a new bookmark var win = mybrowser.contentwindow; // get the bookmarks service const bmsvc = components.classes["@mozilla.org/browser/bookmarks-service;1"] .getservice(components.interfaces.nsibookmarksservice); // create the bookmark bmsvc.createbookmarkincontainer(win.document.title, // bookmark name win.location.href.tostring(), // uri of the bookmark null, // shortcut win.document.title, // description win.document.characterset, // charset null, // postdata bookmarksservice.getbookmarkstoolbarfolder(), // bookmark folder 0); // ...
File I/O - Archive of obsolete content
// you can read it into a string with var data = netutil.readinputstreamtostring(inputstream, inputstream.available()); }); read with content type hint it's useful to provide a content type hint to prevent the file system from doing a potentially expensive content type look up (which would be synchronous i/o).
Rosetta - Archive of obsolete content
ment; this.appendcompiler = function (vmimetypes, fcompiler) { if (arguments.length < 2) { throw new typeerror("rosetta.appendcompiler() \u2013 not enough arguments"); } if (typeof fcompiler !== "function") { throw new typeerror("rosetta.appendcompiler() \u2013 second argument must be a function"); } if (!array.isarray(vmimetypes)) { odicts[(vmimetypes).tostring()] = fcompiler; return true; } for (var nidx = 0; nidx < vmimetypes.length; nidx++) { odicts[(vmimetypes[nidx]).tostring()] = fcompiler; } return true; }; })(); now, imagine you need a compiler for scripts written in c (mime type: text/x-c).
Interaction between privileged and non-privileged pages - Archive of obsolete content
dataxml.tostring() : ""); var event = targetdoc.createevent("event") event.initevent(type, true, true); el.dispatchevent(event); } /** * verifies that the event is indeed coming from our page * as expected, and returns the data for that event.
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
use stringhead(), substring(), and stringtail() instead: nsstring buffer = somestring; - nscautostring prefix;- buffer.left(prefix, 4); + const nsdependentsubstring prefix = stringhead(buffer, 4); the frozen string api doesn't use nssubstringtuple objects and maintains all strings in a contiguous buffer.
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
tream); filestream.init(file, 1, 0, false); var binarystream = components.classes['@mozilla.org/binaryinputstream;1'] .createinstance(components.interfaces.nsibinaryinputstream); binarystream.setinputstream(filestream); var array = binarystream.readbytearray(filestream.available()); binarystream.close(); filestream.close(); alert(array.map( function(aitem) {return aitem.tostring(16); } ).join(' ').touppercase( )); when we initialized nsifileinputstream, we set the second and third parameters to initialize it in read-only mode.
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
overriding/extending/amending existing functions a common thing add-ons do during their initialization is overriding/extending existing browser functions by using function.tostring/function.tosource and eval to "string-patch" the function body.
Code snippets - Archive of obsolete content
components.utils.import("resource://services-sync/engines.js"); components.utils.import("resource://services-sync/engines/bookmarks.js"); let bme = weave.service.enginemanager.get("bookmarks"); let ids = object.keys(bme._store.getallids()); for each (let id in ids) { let record = bme._store.createrecord(id, "bookmarks"); let len = record.tostring().length; if (len > 1000) { console.log("id: " + id + ", len = " + len + ", " + record.title); } } print an alphabetically sorted list of members of a collection components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); let ids = json.parse(new resource(weave.service.storageurl + "bookmarks").get()); for each (let id in...
Basics - Archive of obsolete content
blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded.
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
examples before running any examples, import the api from the future: jetpack.future.import("menu"); snippets add a single, static menuitem to the jetpack menu that doesn't do anything: jetpack.menu.add("two drink holders and a captain's chair"); add a menuitem to the jetpack menu that displays the current date and time each time it's opened: jetpack.menu.add(function () new date().tostring()); click an item in the jetpack menu to be notified of the current date and time: jetpack.menu.add({ label: "show current date and time", command: function () jetpack.notifications.show(new date()) }); the same, except on the content context menu: jetpack.menu.context.page.add({ label: "show current date and time", command: function () jetpack.notifications.show(new date()) }); create...
File object - Archive of obsolete content
xxx file.tostring() returns the canonical path to the file.
Methods - Archive of obsolete content
tostring converts an installversion init to a string.
InstallVersion Object - Archive of obsolete content
the init() method associates a particular version with an installversion object, the tostring() method converts versions in various formats to a string, and the compareto() method compares these string and indicates the relationship between the two versions.
XPInstall API reference - Archive of obsolete content
ch performinstall refreshplugins registerchrome reseterror setpackagefolder installtrigger no properties methods compareversion enabled getversion install installchrome startsoftwareupdate installversion properties methods compareto init tostring file no properties methods copy dircreate dirgetparent dirremove dirrename diskspaceavailable execute exists isdirectory isfile macalias moddate moddatechanged move remove rename size windowsgetshortname windowsregister...
Namespaces - Archive of obsolete content
namespace differs in its tostring method, and in that it has a prefix property instead of a localname property.
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
s (not yet implemented; in other browsers) regexp unicode property escapes (not yet implemented; in other browsers) regexp named capture groups (not yet implemented; in other browsers) ecmascript 2019 array.flat() (firefox 62) array.flatmap() (firefox 62) object.fromentries() (firefox 63) string.trimstart() and string.trimend() (firefox 61) optional catch binding (firefox 58) function.tostring() revision (firefox 54) symbol.description (firefox 63) well-formed json.stringify() (firefox 64) ecmascript 2020 this is the current es.next version.
New in JavaScript 1.1 - Archive of obsolete content
tostring(): added radix parameter, which specifies the base to use for representing numeric values.
New in JavaScript 1.2 - Archive of obsolete content
tostring(): now converts the object or array to a literal.
New in JavaScript 1.3 - Archive of obsolete content
changes to tostring().
New in JavaScript 1.8.5 - Archive of obsolete content
strict mode support array.tostring() now works even on non-arrays by either returning the result of calling its join() method if one is available or by calling its tostring() method.
Object.prototype.watch() - Archive of obsolete content
class person { constructor(name, age) { this.watch('age', this._isvalidassignment.bind(this)); this.watch('name', this._isvalidassignment.bind(this)); this.name = name; this.age = age; } tostring() { return this.name + ', ' + this.age; } _isvalidassignment(id, oldval, newval) { if (id === 'name' && (!newval || newval.length > 30)) { throw new rangeerror('invalid name for ' + this); } if (id === 'age' && (newval < 0 || newval > 200)) { throw new rangeerror('invalid age for ' + this); } return newval; } } const will = new person('will', 29); cons...
Old Proxy API - Archive of obsolete content
var p = proxy.create({get: function(receiver, name) { print(receiver); // looks for receiver's tostring method.
Parsing microformats in JavaScript - Archive of obsolete content
the functions you can call on the returned object are: string = html.tostring(); returns a string using innertext().
Debugging on Windows
here are some entries that will make your life easier: ;; mozilla (1.7beta and later) nsautostring=<mdata,su> nsstring=<mdata,su> nscstring=<mdata,s> nscautostring=<mdata,s> nsrect=x=<x,d> y=<y,d> width=<width,d>; height=<height,d> nsstaticatomwrapper=<mstaticatom->mstring,s> nsiatom=<mstring,su> ; the following are not necessary in vc8 nscomptr<*>=<mrawptr,x> nsrefptr=<mrawptr,x> nsautoptr=<mrawptr,x> after you have made the changes and saved the file, you will need to restart visual c++ fo...
How to implement a custom autocomplete search component
ts.results.ns_error_no_interface; }, canunload: function(acompmgr) { return true; } }; // module initialization function nsgetmodule(acompmgr, afilespec) { return simpleautocompletesearchmodule; } starting in gecko 2.0, component registration has been changed, so you need to make the following changes: add an nsgetfactory() function: function nsgetfactory(cid) { if (cid.tostring().touppercase() != class_id.tostring().touppercase()) { throw components.results.ns_error_factory_not_registered; } return simpleautocompletesearchfactory; } you need to explicitly register the component by adding these lines into your chrome.manifest file: component {6224daa1-71x2-4d1a-ad90-01ca1c08e323} components/.js contract @mozilla.org/autocomplete/search...
Network Addresses
pr_initializenetaddr converting between a string and a network address pr_stringtonetaddr pr_netaddrtostring converting address formats pr_convertipv4addrtoipv6 getting host names and addresses pr_gethostbyname pr_gethostbyaddr pr_enumeratehostent pr_getaddrinfobyname pr_enumerateaddrinfo pr_getcanonnamefromaddrinfo pr_freeaddrinfo getting protocol entries pr_getprotobyname pr_getprotobynumber ...
NSS functions
ficate mxr 3.2 and later nss_cmssignerinfo_getsigningtime mxr 3.2 and later nss_cmssignerinfo_getverificationstatus mxr 3.2 and later nss_cmssignerinfo_getversion mxr 3.2 and later nss_cmssignerinfo_includecerts mxr 3.2 and later nss_cmsutil_verificationstatustostring mxr 3.2 and later nss_smimesignerinfo_savesmimeprofile mxr 3.4 and later nss_smimeutil_findbulkalgforrecipients mxr 3.2 and later pkcs #7 functions the public functions listed here perform pkcs #7 operations required by mail and news applications and by some of the nss tools.
S/MIME functions
ficate mxr 3.2 and later nss_cmssignerinfo_getsigningtime mxr 3.2 and later nss_cmssignerinfo_getverificationstatus mxr 3.2 and later nss_cmssignerinfo_getversion mxr 3.2 and later nss_cmssignerinfo_includecerts mxr 3.2 and later nss_cmsutil_verificationstatustostring mxr 3.2 and later nss_smimesignerinfo_savesmimeprofile mxr 3.4 and later nss_smimeutil_findbulkalgforrecipients mxr 3.2 and later ...
Rhino overview
array.prototype.tostring and object.prototype.tostring version 1.2 only returns array or object literal notation ("[1]" or "{a:1, b:2}" for example).
Performance Hints
for example, the code function myobject(a) { this.s = a; this.tostring = new function("return this.s"); } could be written more efficiently as function myobject(a) { this.s = a; this.tostring = function () { return this.s } } beginning with rhino 1.4 release 2, code passed to eval and new function will be interpreted rather than compiled to class files.
Scripting Java
using the javascript for..in construct, we can print out all these values: js> for (i in f) { print(i) } exists parentfile mkdir tostring wait [44 others] note that not only the methods of the file class are listed, but also the methods inherited from the base class java.lang.object (like wait).
Exact Stack Rooting
instead, spidermonkey has a convenient suite of c++ raii classes to do this for you, called js::rootedt: rootedstring str1(cx, js_valuetostring(cx, val)); rootedstring str2(rt, js_valuetostring(cx, val)); note 1: c++ insists that an initializing assignment (e.g., the default constructor followed by operator=) must have a copy constructor available, even if it is not used.
Property cache
nor do operations such as add that only need to look up a property (.tostring) in unusual cases.
JSAPI User Guide
if a js::value contains a jsobject, double, or jsstring, you can cast it to its underlying data type using the toobject(), todouble(), and tostring() member functions, respectively.
JSExtendedClass.wrappedObject
the specific cases where this happens are: the default tostring method returns a string that contains the name of the wrapped object's class rather than the wrapper's class.
JSVAL_TO_STRING
to coerce any value to a string, use the js_valuetostring function instead.
JS_CompareStrings
see also mxr id search for js_comparestrings js_convertvalue js_getstringchars js_getstringlength js_valuetostring ...
JS_ConvertValue
converting to jstype_string works like js::tostring.
JS_GetStringBytes
see also js_encodestring js_encodestringtoutf8 js_getstringencodinglength js_encodestringtobuffer js_comparestrings js_getstringlength js_valuetostring bug 607292 ...
JS_GetStringLength
see also mxr id search for js_getstringlength js_comparestrings js_convertvalue js_getemptystringvalue js_getstringbytes js_internstring js_newstringcopyn js_newstringcopyz js_valuetostring ...
JS_GetTypeName
literal jstype_void "undefined" jstype_object "object" jstype_function "function" jstype_string "string" jstype_number "number" jstype_boolean "boolean" any other value null see also js_convertvalue js_typeofvalue js_valuetoboolean js_valuetofunction js_valuetoint32 js_valuetonumber js_valuetoobject js_valuetostring bug 1037718 ...
JS_GetVersion
see also mxr id search for js_getversion js_versiontostring js_stringtoversion js_setversionforcompartment ...
JS_InternString
see also mxr id search for js_internstring mxr id search for js_internstringn mxr id search for js_internucstring mxr id search for js_internucstringn js_getemptystringvalue js_newstringcopyn js_newstringcopyz js_newucstring js_newucstringcopyn js_newucstringcopyz js_valuetostring ...
JS_NewUCString
see also js_convertvalue js_getemptystringvalue js_getstringbytes js_getstringchars js_getstringlength js_internstring js_internucstring js_internucstringn js_newstringcopyn js_newstringcopyz js_newucstringcopyn js_newucstringcopyz js_valuetostring bug 618262 - removed js_newstring ...
JS_NewStringCopyN
see also mxr id search for js_newstringcopyn mxr id search for js_newucstringcopyn js_getemptystringvalue js_newstringcopyz js_newucstringcopyz js_valuetostring ...
JS_NewStringCopyZ
see also mxr id search for js_newstringcopyz mxr id search for js_newucstringcopyz js_getemptystringvalue js_newstringcopyn js_newucstringcopyn js_valuetostring ...
JS_PropertyStub
it attempts to call the object's valueof and tostring functions, in the order determined by the specified type, in accordance with the default defaultvalue algorithm in es5 §8.12.8.
JS_SetVersion
see also mxr id search for js_setversion jsversion js_getversion js_versiontostring js_stringtoversion bug 880917 ...
JS_SetVersionForCompartment
see also mxr id search for js_setversionforcompartment jsversion js_getversion js_versiontostring js_stringtoversion bug 880917 ...
JS_StringToVersion
24 "1.4" jsversion_1_4 obsolete since jsapi 24 "ecmav3" jsversion_ecma_3 "1.5" jsversion_1_5 obsolete since jsapi 24 "1.6" jsversion_1_6 "1.7" jsversion_1_7 "1.8" jsversion_1_8 other jsversion_unknown see also mxr id search for js_stringtoversion jsversion js_getversion js_setversionforcompartment js_versiontostring bug 824312 ...
JS_TypeOfValue
see also mxr id search for js_typeofvalue js_convertvalue js_gettypename js_valuetoboolean js_valuetofunction js_valuetoint32 js_valuetonumber js_valuetoobject js_valuetostring ...
JS_ValueToId
if v is not a string, it is converted to a string as if by calling js_valuetostring.
JS_ValueToNumber
otherwise, the resulting object's tostring method, if any, is called.
SpiderMonkey 31
aced by js::toboolean) js_valuetonumber (can be replaced with js::tonumber) js_valuetoint64 (replaced by js::toint64) js_valuetouint64 (replaced by js::touint64) js_valuetoecmauint32 (replaced by js::touint32) js_valuetoecmaint32 (replaced by js::toint32) js_valuetoint32 (can be replaced with js::toint32, which has a different behavior!) js_valuetouint16 (replaced by js::touint16) js_valuetostring (replaced by js::tostring) js_definepropertywithtinyid js_defineucpropertywithtinyid js_getobjectid api changes spidermonkey must now be initialized before it can be used.
SavedFrame
function properties of the savedframe.prototype object tostring return this frame and its parents formatted as a human readable stack trace string.
Shell global objects
{ tostring } apply js::tostring to params.tostring.
An Overview of XPCOM
of the three methods on the nsiid class, equals, parse, and tostring, equals is by far the most important, because it is used to compare two nsiids in this interface querying process.
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
netutil.jsm provides apis for copying an input stream to an output stream (the asynccopy() method), getting an input stream from another source (the asyncfetch() method), and reading an input stream into a string (the readinputstreamtostring() method).
XPConnect wrappers
if you call 'tostring()' and get "[xpconnect wrapped nsifoo]" then the reference is to a xpcwrappednative object with interface nsifoo.
nsACString (External)
a alt="" coords="731,198,955,246" href="http://developer.mozilla.org/en/nsdependentcsubstring_external" shape="rect" title="nsdependentcsubstring_external"> <area alt="" coords="979,198,1123,246" href="http://developer.mozilla.org/en/promiseflatcstring_(external)" shape="rect" title="promiseflatcstring_(external)"> <area alt="" coords="1147,198,1259,246" href="http://developer.mozilla.org/en/nscautostring_(external)" shape="rect" title="nscautostring_(external)"> <area alt="" coords="5,294,208,342" href="http://developer.mozilla.org/en/nsdependentcstring_external" shape="rect" title="nsdependentcstring_external"> <area alt="" coords="232,294,475,342" href="http://developer.mozilla.org/en/ns_convertutf16toutf8_external" shape="rect" title="ns_convertutf16toutf8_external"> <area alt="" coords="499,2...
nsACString_internal
ng" shape="rect" title="nsxpidlcstring"> <area alt="" coords="461,197,611,245" href="http://developer.mozilla.org/en/nsdependentcstring" shape="rect" title="nsdependentcstring"> <area alt="" coords="635,197,787,245" href="http://developer.mozilla.org/en/nspromiseflatcstring" shape="rect" title="nspromiseflatcstring"> <area alt="" coords="173,293,285,341" href="http://developer.mozilla.org/en/nscautostring" shape="rect" title="nscautostring"> <area alt="" coords="5,389,227,437" href="http://developer.mozilla.org/en/ns_lossyconvertutf16toascii" shape="rect" title="ns_lossyconvertutf16toascii"> <area alt="" coords="251,389,435,437" href="http://developer.mozilla.org/en/ns_convertutf16toutf8" shape="rect" title="ns_convertutf16toutf8"> <area alt="" coords="309,293,445,341" href="http://developer.mozil...
nsAString (External)
<area alt="" coords="700,198,913,246" href="http://developer.mozilla.org/en/nsdependentsubstring_external" shape="rect" title="nsdependentsubstring_external"> <area alt="" coords="937,198,1071,246" href="http://developer.mozilla.org/en/promiseflatstring_(external)" shape="rect" title="promiseflatstring_(external)"> <area alt="" coords="1095,198,1196,246" href="http://developer.mozilla.org/en/nsautostring_(external)" shape="rect" title="nsautostring_(external)"> <area alt="" coords="5,294,197,342" href="http://developer.mozilla.org/en/nsdependentstring_external" shape="rect" title="nsdependentstring_external"> <area alt="" coords="221,294,467,342" href="http://developer.mozilla.org/en/ns_convertasciitoutf16_external" shape="rect" title="ns_convertasciitoutf16_external"> <area alt="" coords="491,29...
nsAString_internal
dlstring" shape="rect" title="nsxpidlstring"> <area alt="" coords="420,197,559,245" href="http://developer.mozilla.org/en/nsdependentstring" shape="rect" title="nsdependentstring"> <area alt="" coords="583,197,727,245" href="http://developer.mozilla.org/en/nspromiseflatstring" shape="rect" title="nspromiseflatstring"> <area alt="" coords="152,293,253,341" href="http://developer.mozilla.org/en/nsautostring" shape="rect" title="nsautostring"> <area alt="" coords="5,389,192,437" href="http://developer.mozilla.org/en/ns_convertasciitoutf16" shape="rect" title="ns_convertasciitoutf16"> <area alt="" coords="216,389,400,437" href="http://developer.mozilla.org/en/ns_convertutf8toutf16" shape="rect" title="ns_convertutf8toutf16"> <area alt="" coords="277,293,405,341" href="http://developer.mozilla.org/en/n...
XPCOM glue classes
r arrays.nsastring (external)class declarationnsastring_internalclass declarationnsautorefnsautoref<t> is a template class implementing an object that holds a handle to a resource that must be released, typically on destruction of the object.</t>nsautoreftraitsnsautoreftraits<t> is a template class describing traits of resources held by objects of class nsautoref<t> and/or nscountedref<t>.</t>nsautostringclass declarationnsautostring (external)class declarationnscautostringclass declarationnscautostring (external)class declarationnscomptrthis utility class simplifies managing xpcom interface references from c++ code.nscountedrefnscountedref<t> is a template class implementing an object that takes a strong reference to a reference-counted resource that must be released, typically on destruction of ...
nsIDOMNSHTMLDocument
return value the text of the current selection, the same as window.getselection.tostring().
nsIMsgAccount
inherits from: nsisupports last changed in gecko 1.7 method overview void addidentity(in nsimsgidentity identity); void clearallvalues(); void init(); void removeidentity(in nsimsgidentity identity); astring tostring(); attributes attribute type description defaultidentity nsimsgidentity identities nsisupportsarray read only.
nsIMsgSearchValue
* (range 0-100, 100 is junk) */ attribute unsigned long junkpercent; astring tostring(); }; ...
nsIScriptableInputStream
note: starting in gecko 2.0, you can use the netutils.jsm javascript code module and its readinputstreamtostring() method to read arbitrary binary data into a javascript string.
nsIUUIDGenerator
exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) example generating a uuid var uuidgenerator = components.classes["@mozilla.org/uuid-generator;1"] .getservice(components.interfaces.nsiuuidgenerator); var uuid = uuidgenerator.generateuuid(); var uuidstring = uuid.tostring(); ...
nsIMsgSearchValue
* (range 0-100, 100 is junk) */ attribute unsigned long junkpercent; astring tostring(); }; ...
Mail and RDF
s might work inside the datasource: var msgcountarc = rdf.getresource("http://home.netscape.com/nc-rdf#totalmessages"); function gettarget(target, property, unused) { var folder = target.queryinterface(components.interfaces.nsimsgfolder); if (property == msgcountarc) { var msgcount = folder.gettotalmessages(false); var result = rdf.getliteral(msgcount.tostring()); return result; } } asynchronously notifying rdf when a mail object's data changes and the data is reflected in rdf by notifying all of the observers that rdf has registered with the datasource.
Using COM from js-ctypes
e', winabi, hresult, // return refclsid, // rclsid lpunknown, // punkouter dword, // dwclscontext refiid, // riid lpvoid // *ppv ); // helper functions function checkhresult(hr /*primative hresult*/, funcname /*jsstr*/) { // primative because thats what is returned by declared functions that // return hresult hr = hr.tostring(); // makes it primative if (hr < 0) { console.error('hresult', hr, 'returned from function ', funcname /*, 'getstrofresult:', getstrofresult(hr)*/); throw new error('hresult ' + hr + ' returned from function ' + funcname); } } let clsidfromarr = iidfromarr = function(jsarr_pieces) { let guid = guid(); // clsid and iid are same they are guid ...
Using js-ctypes
acters(null, jsstr, jsstr.length); } // main var mycfstrs = { head: makecfstr('core foundation says...'), body: makecfstr('we just called the equivalent of the "standardalert carbon function" for 64bit osx from javascript!') }; var rez = cfusernotificationdisplaynotice(0, kcfusernotificationcautionalertlevel, null, null, null, mycfstrs.head, mycfstrs.body, null); console.info('rez:', rez, rez.tostring(), uneval(rez)); // cfusernotificationdisplaynotice does not block till user clicks dialog, it will return immediately if (rez.tostring() == '0') { console.log('notification was succesfully shown!!'); } else { console.error('failed to show notification...
FunctionType
method overview methods inherited from ctype ctype array([n]) string tosource() string tostring() functiontype cdata functiontype cdata cannot be constructed.
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
plot(log); } function handleuncaughtexception(ex) { console.log('debugger hook threw:'); console.log(ex.tostring()); console.log('stack:'); console.log(ex.stack); }; function plot(log) { // given the log, compute a map from allocation sites to // allocation counts.
Waterfall - Firefox Developer Tools
for example, suppose we adapt the code above to make a timestamp every 10 iterations of the loop, labeled with the iteration number: var iterations = 70; var multiplier = 1000000000; function calculateprimes() { console.time("calculating..."); var primes = []; for (var i = 0; i < iterations; i++) { if (i % 10 == 0) { console.timestamp(i.tostring()); } var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } } console.timeend("calculating..."); return primes; } in the waterfall you'll n...
Web Console remoting - Firefox Developer Tools
exceptionmessage holds the exception.tostring() result.
CSSImageValue - Web APIs
then get() the background-image from the stylemap and stringify it: // get the element const button = document.queryselector( 'button' ); // retrieve all computed styles with computedstylemap() const allcomputedstyles = button.computedstylemap(); // return the cssimagevalue example console.log( allcomputedstyles.get('background-image') ); console.log( allcomputedstyles.get('background-image').tostring() ); specifications specification status comment css typed om level 1the definition of 'cssimagevalue' in that specification.
CSSNumericValue.add() - Web APIs
examples let mathsum = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); // prints "calc(23px + 4% + 3cm + 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'add' in that specification.
CSSNumericValue.div() - Web APIs
examples let mathproduct = css.px("24").div(css.percent("4")); // prints "calc(24px / 4%)" mathproduct.tostring(); specifications specification status comment css typed om level 1the definition of 'div' in that specification.
CSSNumericValue.max() - Web APIs
// prints "2cm" console.log(css.cm("1").max(css.cm("2")).tostring()); // prints "max(1cm, 0.393701in)" console.log(css.cm("1").max(css.in("0.393701")).tostring()); specifications specification status comment css typed om level 1the definition of 'max' in that specification.
CSSNumericValue.min() - Web APIs
// prints "1cm" console.log(css.cm("1").min(css.cm("2")).tostring()); // prints "max(1cm, 0.393701in)" console.log(css.cm("1").max(css.in("0.393701")).tostring()); specifications specification status comment css typed om level 1the definition of 'min' in that specification.
CSSNumericValue.mul() - Web APIs
examples let mathsum = css.px("23").mul(css.percent("4")).mul(css.cm("3")).mul(css.in("9")); // prints "calc(23px * 4% * 3cm * 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'mul' in that specification.
CSSNumericValue.sub() - Web APIs
examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification.
CSSNumericValue.sum() - Web APIs
examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification.
CSSNumericValue.to() - Web APIs
examples // prints "0.608542cm" console.log(css.px("23").to("com").tostring()); specifications specification status comment css typed om level 1the definition of 'to' in that specification.
CSSNumericValue.toSum() - Web APIs
examples let v = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); v.tostring() // => "calc(23px + 4% + 3cm + 9in)" v.tosum("px", "percent").tostring() // => "calc(1000.39px + 4%)" specifications specification status comment css typed om level 1the definition of 'tosum' in that specification.
CSS Painting API - Web APIs
nputproperties() { return ['--boxcolor']; } static get inputarguments() { return ['*','<length>']; } static get contextoptions() { return {alpha: true}; } paint(ctx, size, props, args) { const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; const thecolor = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strokewidth = parseint(args[1]); console.log(thecolor); if ( strokewidth ) { ctx.linewidth = strokewidth; } else { ctx.linewidth = 1.0; } if ( stroketype === 'stroke' ) { ctx.fillstyle = 'transparent'; ctx.strokestyle = thecolor; } else if ( stroketype === 'filled' ) { ctx.fillstyle = thecolor; ctx.strokestyle = thecolor; } else { ctx.fillstyle =...
DOMMatrixReadOnly.flipX() - Web APIs
const flipped = document.getelementbyid('flipped'); const matrix = new dommatrixreadonly(); const flippedmatrix = matrix.flipx(); flipped.setattribute('transform', flippedmatrix.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.flipx()' in that specification.
DOMMatrixReadOnly.scale() - Web APIs
dmatrixwithorigin = matrix.scale(0.5, 25, 25); // if the browser has interpreted these parameters as scalex, scaley, scalez, the resulting matrix is 3d const browserexpectssixparamscale = !scaledmatrixwithorigin.is2d; if (browserexpectssixparamscale) { scaledmatrixwithorigin = matrix.scale(0.5, 0.5, 1, 25, 25, 0); } document.queryselector('#transformed').setattribute('transform', scaledmatrix.tostring()); document.queryselector('#transformedorigin').setattribute('transform', scaledmatrixwithorigin.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.scale()' in that specification.
DOMMatrixReadOnly.translate() - Web APIs
const matrix = new dommatrixreadonly().translate(25, 25); document.queryselector('#transformed').setattribute('transform', matrix.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.translate()' in that specification.
DOMMatrixReadOnly - Web APIs
dommatrixreadonly.tostring() creates and returns a domstring object which contains a string representation of the matrix in css matrix syntax, using the appropriate css matrix notation.
DirectoryReaderSync - Web APIs
function onerror(e) { postmessage('error: ' + e.tostring()); } self.onmessage = function(e) { var data = e.data; // ignore everything else except our 'list' command.
Document.createCDATASection() - Web APIs
example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml') var cdata = docu.createcdatasection('some <cdata> data & then some'); docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err.
Document.createComment() - Web APIs
example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml'); var comment = docu.createcomment('this is a not-so-secret comment in your document'); docu.getelementsbytagname('xml')[0].appendchild(comment); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><!--this is a not-so-secret comment in your document--></xml> specifications specification status comment domthe definition of 'document.createcomment' in that specification.
Document.createProcessingInstruction() - Web APIs
example var doc = new domparser().parsefromstring('<foo />', 'application/xml'); var pi = doc.createprocessinginstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'); doc.insertbefore(pi, doc.firstchild); console.log(new xmlserializer().serializetostring(doc)); // displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/> specifications specification status comment domthe definition of 'createprocessinginstruction()' in that specification.
Document.mozSetImageElement() - Web APIs
var c = 0x00; function clicked() { var canvas = document.createelement("canvas"); canvas.setattribute("width", 100); canvas.setattribute("height", 100); var ctx = canvas.getcontext('2d'); ctx.fillstyle = "#" + c.tostring(16) + "0000"; ctx.fillrect(25, 25, 75, 75); c += 0x11; if (c > 0xff) { c = 0x00; } document.mozsetimageelement("canvasbg", canvas); } the code here is called each time the user clicks the <div> element.
Element.classList - Web APIs
WebAPIElementclassList
") (function(window){ var document = window.document, object = window.object, hasownprop = object.prototype.hasownproperty; var defineproperty = object.defineproperty, allowtokenlistconstruction = 0, skippropchange = 0; function domtokenlist(){ if (!allowtokenlistconstruction) throw typeerror("illegal constructor"); // internally let it through } domtokenlist.prototype.tostring = domtokenlist.prototype.tolocalestring = function(){return this.value}; domtokenlist.prototype.add = function(){ a: for(var v=0, arglen=arguments.length,val="",ele=this[" ucl"],proto=ele[" uclp"]; v!==arglen; ++v) { val = arguments[v] + "", checkifvalidclasslistentry("add", val); for (var i=0, len=proto.length, resstr=val; i !== len; ++i) if (t...
Element: copy event - Web APIs
e">...and pasting it into this one</div> css div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const source = document.queryselector('div.source'); source.addeventlistener('copy', (event) => { const selection = document.getselection(); event.clipboarddata.setdata('text/plain', selection.tostring().touppercase()); event.preventdefault(); }); result specifications specification status clipboard api and events working draft ...
Element: cut event - Web APIs
WebAPIElementcut event
ue">...and pasting it into this one</div> css div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const source = document.queryselector('div.source'); source.addeventlistener('cut', (event) => { const selection = document.getselection(); event.clipboarddata.setdata('text/plain', selection.tostring().touppercase()); selection.deletefromdocument(); event.preventdefault(); }); result specifications specification status clipboard api and events working draft ...
Using Fetch - Web APIs
a headers object is a simple multi-map of names to values: const content = 'hello world'; const myheaders = new headers(); myheaders.append('content-type', 'text/plain'); myheaders.append('content-length', content.length.tostring()); myheaders.append('x-custom-header', 'processthisimmediately'); the same can be achieved by passing an array of arrays or an object literal to the constructor: const myheaders = new headers({ 'content-type': 'text/plain', 'content-length': content.length.tostring(), 'x-custom-header': 'processthisimmediately' }); the contents can be queried and retrieved: console.log(myheaders.has(...
FileException - Web APIs
when errors occur, forward them to the main app using postmessage() as in the following: function onerror(e) { postmessage('error:' + e.tostring()); } try { //error is thrown if "log.txt" already exists.
FileSystemFileEntry - Web APIs
fileentry.createwriter(function(filewriter) { filewriter.onwriteend = function(e) { console.log('write completed.'); }; filewriter.onerror = function(e) { console.log('write failed: ' + e.tostring()); }; // create a new blob and write it to log.txt.
HTMLAnchorElement - Web APIs
htmlhyperlinkelementutils.tostring() returns a usvstring containing the whole url.
HTMLAreaElement - Web APIs
htmlhyperlinkelementutils.tostring() returns a usvstring containing the whole url of the script executed in the worker.
HTMLHyperlinkElementUtils - Web APIs
htmlhyperlinkelementutils.tostring() this returns a usvstring containing the whole url.
Timing element visibility with the Intersection Observer API - Web APIs
this is handled by passing the ad's element into the drawadtimer() function: function drawadtimer(adbox) { let timerbox = adbox.queryselector(".timer"); let totalseconds = adbox.dataset.totalviewtime / 1000; let sec = math.floor(totalseconds % 60); let min = math.floor(totalseconds / 60); timerbox.innertext = min + ":" + sec.tostring().padstart(2, "0"); } this code finds the ad's timer using its id, "timer", and computes the number of seconds elapsed by dividing the ad's totalviewtime by 1000.
Location - Web APIs
WebAPILocation
location.tostring() returns a usvstring containing the whole url.
PluginArray - Web APIs
var pluginslength = navigator.plugins.length; document.write( pluginslength.tostring() + " plugin(s)<br>" + "name | filename | description<br>" ); for(var i = 0; i < pluginslength; i++) { document.write( navigator.plugins[i].name + " | " + navigator.plugins[i].filename + " | " + navigator.plugins[i].description + " | " + navigator.plugins[i].version + "<br>" ); } specifications specification status comment html ...
Using Pointer Events - Web APIs
function colorfortouch(touch) { var r = touch.pointerid % 16; var g = math.floor(touch.pointerid / 3) % 16; var b = math.floor(touch.pointerid / 7) % 16; r = r.tostring(16); // make it a hex digit g = g.tostring(16); // make it a hex digit b = b.tostring(16); // make it a hex digit var color = "#" + r + g + b; log("color for touch with identifier " + touch.pointerid + " = " + color); return color; } the result from this function is a string that can be used when calling <canvas> functions to set drawing colors.
RTCDataChannel.binaryType - Web APIs
var dc = peerconnection.createdatachannel("binary"); dc.binarytype = "arraybuffer"; dc.onmessage = function(event) { let bytearray = new uint8array(event.data); let hexstring = ""; bytearray.foreach(function(byte) { hexstring += byte.tostring(16) + " "; }); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.binarytype' in that specification.
Range - Web APIs
WebAPIRange
range.tostring() returns the text of the range.
SVGGraphicsElement: copy event - Web APIs
90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" placeholder="paste it here"/> </foreignobject> </svg> css input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; } javascript document.getelementsbytagname("text")[0].addeventlistener("copy", evt => { evt.clipboarddata.setdata('text/plain', document.getselection().tostring().touppercase()); evt.preventdefault(); }); result specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation definition that the clipboard events apply to svg elements.
Selection.setBaseAndExtent() - Web APIs
'.two'); var aoffset = document.getelementbyid('aoffset'); var foffset = document.getelementbyid('foffset'); var button = document.queryselector('button'); var output = document.queryselector('.output'); var selection; button.onclick = function() { try { selection = document.getselection(); selection.setbaseandextent(one, aoffset.value, two, foffset.value); var text = selection.tostring(); output.textcontent = text; } catch(e) { output.textcontent = e.message; } } play with the live example below, setting different offset values to see how this affects the selection.
SubtleCrypto.digest() - Web APIs
nc function digestmessage(message) { const msguint8 = new textencoder().encode(message); // encode as (utf-8) uint8array const hashbuffer = await crypto.subtle.digest('sha-256', msguint8); // hash the message const hasharray = array.from(new uint8array(hashbuffer)); // convert buffer to byte array const hashhex = hasharray.map(b => b.tostring(16).padstart(2, '0')).join(''); // convert bytes to hex string return hashhex; } const digesthex = await digestmessage(text); console.log(digesthex); specifications specification status comment web cryptography apithe definition of 'subtlecrypto.digest()' in that specification.
Touch events - Web APIs
function colorfortouch(touch) { var r = touch.identifier % 16; var g = math.floor(touch.identifier / 3) % 16; var b = math.floor(touch.identifier / 7) % 16; r = r.tostring(16); // make it a hex digit g = g.tostring(16); // make it a hex digit b = b.tostring(16); // make it a hex digit var color = "#" + r + g + b; console.log("color for touch with identifier " + touch.identifier + " = " + color); return color; } the result from this function is a string that can be used when calling <canvas> functions to set drawing colors.
URLSearchParams.sort() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("c=4&a=2&b=3&a=1"); // sort the key/value pairs searchparams.sort(); // display the sorted query string console.log(searchparams.tostring()); the result is: a=2&a=1&b=3&c=4 specifications specification status comment urlthe definition of 'sort()' in that specification.
VideoPlaybackQuality.droppedVideoFrames - Web APIs
var videoelem = document.getelementbyid("my_vid"); var percentelem = document.getelementbyid("percent"); var quality = videoelem.getvideoplaybackquality(); var droppercent = (quality.droppedvideoframes/quality.totalvideoframes)*100; percentelem.innertext = math.trunc(droppercent).tostring(10); specifications specification status comment media playback qualitythe definition of 'videoplaybackquality.droppedvideoframes' in that specification.
Writing a WebSocket server in Java - Web APIs
if (get.find()) { matcher match = pattern.compile("sec-websocket-key: (.*)").matcher(data); match.find(); byte[] response = ("http/1.1 101 switching protocols\r\n" + "connection: upgrade\r\n" + "upgrade: websocket\r\n" + "sec-websocket-accept: " + base64.getencoder().encodetostring(messagedigest.getinstance("sha-1").digest((match.group(1) + "258eafa5-e914-47da-95ca-c5ab0dc85b11").getbytes("utf-8"))) + "\r\n\r\n").getbytes("utf-8"); out.write(response, 0, response.length); decoding messages after a successful handshake, client can send messages to the server, but now these are encoded.
Using Web Workers - Web APIs
for example: function fn2workerurl(fn) { var blob = new blob(['('+fn.tostring()+')()'], {type: 'application/javascript'}) return url.createobjecturl(blob) } further examples this section provides further examples of how to use web workers.
Window.name - Web APIs
WebAPIWindowname
window.name will convert all values to their string representations by using the tostring method.
WindowOrWorkerGlobalScope.btoa() - Web APIs
so if you pass a string into btoa() containing characters that occupy more than one byte, you will get an error, because this is not considered binary data: const ok = "a"; console.log(ok.codepointat(0).tostring(16)); // 61: occupies < 1 byte const notok = "✓" console.log(notok.codepointat(0).tostring(16)); // 2713: occupies > 1 byte console.log(btoa(ok)); // yq== console.log(btoa(notok)); // error if you need to encode unicode text as ascii using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte.
WorkerLocation - Web APIs
urlutilsreadonly.tostring() returns a domstring containing the whole url of the script executed in the worker.
XMLDocument.async - Web APIs
WebAPIXMLDocumentasync
(it has been possible to load documents synchronously since 1.4 alpha.) example function loadxmldata(e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } var xmldoc = document.implementation.createdocument("", "test", null); xmldoc.async = false; xmldoc.onload = loadxmldata; xmldoc.load('querydata.xml'); ...
XMLDocument.load() - Web APIs
WebAPIXMLDocumentload
examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory.
Using XMLHttpRequest - Web APIs
"?" + odata.segments.join("&") : ""), true); oajaxreq.send(null); } else { /* method is post */ oajaxreq.open("post", odata.receiver, true); if (odata.technique === 3) { /* enctype is multipart/form-data */ var sboundary = "---------------------------" + date.now().tostring(16); oajaxreq.setrequestheader("content-type", "multipart\/form-data; boundary=" + sboundary); oajaxreq.sendasbinary("--" + sboundary + "\r\n" + odata.segments.join("--" + sboundary + "\r\n") + "--" + sboundary + "--\r\n"); } else { /* enctype is application/x-www-form-urlencoded or text/plain */ oajaxreq.setrequestheader("content-type", odata.con...
Using the slider role - Accessibility
="monday"> </div> </div> the code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes: var daynames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; var updateslider = function (newvalue) { var handle = document.getelementbyid("day-handle"); handle.setattribute("aria-valuenow", newvalue.tostring()); handle.setattribute("aria-valuetext", daynames[newvalue]); }; working examples: slider example notes aria attributes used aria-valuemin aria-valuemax aria-valuenow aria-valuetext aria-orientation related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for the sli...
Box-shadow generator - CSS: Cascading Style Sheets
eturn; if (value[0] === '#') value = value.slice(1, value.length); if (value.length === 3) value = value.replace(/([0-9a-f])([0-9a-f])([0-9a-f])/i,"$1$1$2$2$3$3"); this.r = parseint(value.substr(0, 2), 16); this.g = parseint(value.substr(2, 2), 16); this.b = parseint(value.substr(4, 2), 16); this.alpha = 1; } color.prototype.gethexa = function gethexa() { var r = this.r.tostring(16); var g = this.g.tostring(16); var b = this.b.tostring(16); if (this.r < 16) r = '0' + r; if (this.g < 16) g = '0' + g; if (this.b < 16) b = '0' + b; var value = '#' + r + g + b; return value.touppercase(); } color.prototype.getrgba = function getrgba() { var rgb = "(" + this.r + ", " + this.g + ", " + this.b; var a = ''; var v = ''; if (this.a !== 1) { a = 'a'; ...
Color picker tool - CSS: Cascading Style Sheets
) { hue = 2 + (blue - red) / delta; } if (cmax === blue ) { hue = 4 + (red - green) / delta; } if (cmax) saturation = delta / x; } this.hue = 60 * hue | 0; if (this.hue < 0) this.hue += 360; this.saturation = (saturation * 100) | 0; this.lightness = (lightness * 100) | 0; }; /*========== get methods ==========*/ color.prototype.gethexa = function gethexa() { var r = this.r.tostring(16); var g = this.g.tostring(16); var b = this.b.tostring(16); if (this.r < 16) r = '0' + r; if (this.g < 16) g = '0' + g; if (this.b < 16) b = '0' + b; var value = '#' + r + g + b; return value.touppercase(); }; color.prototype.getrgba = function getrgba() { var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; var a = ''; var v = ''; var x = parsefloat(this.a); if ...
Linear-gradient Generator - CSS: Cascading Style Sheets
) { hue = 2 + (blue - red) / delta; } if (cmax === blue ) { hue = 4 + (red - green) / delta; } if (cmax) saturation = delta / x; } this.hue = 60 * hue | 0; if (this.hue < 0) this.hue += 360; this.saturation = (saturation * 100) | 0; this.lightness = (lightness * 100) | 0; }; /*========== get methods ==========*/ color.prototype.gethexa = function gethexa() { var r = this.r.tostring(16); var g = this.g.tostring(16); var b = this.b.tostring(16); if (this.r < 16) r = '0' + r; if (this.g < 16) g = '0' + g; if (this.b < 16) b = '0' + b; var value = '#' + r + g + b; return value.touppercase(); }; color.prototype.getrgba = function getrgba() { var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; var a = ''; var v = ''; var x = parsefloat(this.a); if ...
Rich-Text Editing in Mozilla - Developer guides
= document.createelement("pre"); odoc.contenteditable = false; opre.id = "sourcetext"; opre.contenteditable = true; opre.appendchild(ocontent); odoc.appendchild(opre); } else { if (document.all) { odoc.innerhtml = odoc.innertext; } else { ocontent = document.createrange(); ocontent.selectnodecontents(odoc.firstchild); odoc.innerhtml = ocontent.tostring(); } odoc.contenteditable = true; } odoc.focus(); } function printdoc() { if (!validatemode()) { return; } var oprntwin = window.open("","_blank","width=450,height=470,left=400,top=100,menubar=yes,toolbar=no,location=no,scrollbars=yes"); oprntwin.document.open(); oprntwin.document.write("<!doctype html><html><head><title>print<\/title><\/head><body onload=\"print();\">" + odo...
Making content editable - Developer guides
opre.id = "sourcetext"; opre.contenteditable = true; opre.appendchild(ocontent); odoc.appendchild(opre); document.execcommand("defaultparagraphseparator", false, "div"); } else { if (document.all) { odoc.innerhtml = odoc.innertext; } else { ocontent = document.createrange(); ocontent.selectnodecontents(odoc.firstchild); odoc.innerhtml = ocontent.tostring(); } odoc.contenteditable = true; } odoc.focus(); } function printdoc() { if (!validatemode()) { return; } var oprntwin = window.open("","_blank","width=450,height=470,left=400,top=100,menubar=yes,toolbar=no,location=no,scrollbars=yes"); oprntwin.document.open(); oprntwin.document.write("<!doctype html><html><head><title>print<\/title><\/head><body onload=\"print();\">" + odo...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
WebHTMLElementdialog
wser"); } }); // "favorite animal" input sets the value of the submit button selectel.addeventlistener('change', function onselect(e) { confirmbtn.value = selectel.value; }); // "confirm" button of form triggers "close" on dialog because of [method="dialog"] favdialog.addeventlistener('close', function onclose() { outputbox.value = favdialog.returnvalue + " button clicked - " + (new date()).tostring(); }); result specifications specification status comment html living standardthe definition of '<dialog>' in that specification.
Equality comparisons and sameness - JavaScript
toprimitive(a) attempts to convert its object argument to a primitive value, by attempting to invoke varying sequences of a.tostring and a.valueof methods on a.
Grammar and types - JavaScript
var obj = { // __proto__ __proto__: theprotoobj, // shorthand for ‘handler: handler’ handler, // methods tostring() { // super calls return 'd ' + super.tostring(); }, // computed (dynamic) property names [ 'prop_' + (() => 42)() ]: 42 }; regexp literals a regex literal (which is defined in detail later) is a pattern enclosed between slashes.
Working with objects - JavaScript
for example, in the above code, when the key obj is added to the myobj, javascript will call the obj.tostring() method, and use this result string as the new key.
TypeError: X.prototype.y called on incompatible type - JavaScript
message typeerror: 'this' is not a set object (edge) typeerror: function.prototype.tostring called on incompatible object (firefox) typeerror: function.prototype.bind called on incompatible target (firefox) typeerror: method set.prototype.add called on incompatible receiver undefined (chrome) typeerror: bind must be called on a function (chrome) error type typeerror what went wrong?
RangeError: invalid date - JavaScript
however, depending on the implementation, non–conforming iso format strings, may also throw rangeerror: invalid date, like the following cases in firefox: new date('foo-bar 2014'); new date('2014-25-23').toisostring(); new date('foo-bar 2014').tostring(); this, however, returns nan in firefox: date.parse('foo-bar 2014'); // nan for more details, see the date.parse() documentation.
Array.prototype.reduce() - JavaScript
tostring(k).
Array.prototype.find() - JavaScript
tostring(k).
Array.prototype.findIndex() - JavaScript
tostring(k).
Array.from() - JavaScript
symbol.iterator : 'symbol(symbol.iterator)'; } catch { symboliterator = 'symbol(symbol.iterator)'; } var tostr = object.prototype.tostring; var iscallable = function (fn) { return ( typeof fn === 'function' || tostr.call(fn) === '[object function]' ); }; var tointeger = function (value) { var number = number(value); if (isnan(number)) return 0; if (number === 0 || !isfinite(number)) return number; return (n...
Array.isArray() - JavaScript
if (!array.isarray) { array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls return true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); array.isarray(new array(3)); // little known fact: array.prototype itself is an array: array.isarray(array.prototype); // all following calls return false array.isarray(); array.
Array.prototype.map() - JavaScript
let pk be tostring(k).
Date.parse() - JavaScript
other examples: new date('foo-bar 2014').tostring(); // returns: "invalid date" date.parse('foo-bar 2014'); // returns: nan differences in assumed time zone this section contains implementation-specific behavior that can be inconsistent across implementations.
Error.prototype.message - JavaScript
the message property combined with the name property is used by the error.prototype.tostring() method to create a string representation of the error.
Function.prototype.bind() - JavaScript
however, provided arguments are still prepended to the constructor call: function point(x, y) { this.x = x; this.y = y; } point.prototype.tostring = function() { return `${this.x},${this.y}`; }; const p = new point(1, 2); p.tostring(); // '1,2' // not supported in the polyfill below, // works fine with native bind: const yaxispoint = point.bind(null, 0/*x*/); const emptyobj = {}; const yaxispoint = point.bind(emptyobj, 0/*x*/); const axispoint = new yaxispoint(5); axispoint.tostring(); // '0,5' axispoint inst...
Intl.Locale.prototype.baseName - JavaScript
examples basic example let myloc = new intl.locale("fr-latn-ca"); // sets locale to canadian french console.log(myloc.tostring()); // prints out "fr-latn-ca-u-ca-gregory" console.log(myloc.basename); // prints out "fr-latn-ca" example with options in the input string // sets language to japanese, region to japan, // calendar to gregorian, hour cycle to 24 hours let japan = new intl.locale("ja-jp-u-ca-gregory-hc-24"); console.log(japan.tostring()); // prints out "ja-jp-u-ca-gregory-hc-h24" console.log(japan.basename); ...
Intl.Locale - JavaScript
intl.locale.prototype.tostring() returns the locale's full locale identifier string.
JSON.parse() - JavaScript
text = string(text); rx_dangerous.lastindex = 0; if (rx_dangerous.test(text)) { text = text.replace(rx_dangerous, function(a) { return ( "\\u" + ("0000" + a.charcodeat(0).tostring(16)).slice(-4) ); }); } // in the second stage, we run the text against regular expressions that look // for non-json patterns.
Number.parseFloat() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
Number.parseInt() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
Number.prototype.toFixed() - JavaScript
if the absolute value of numobj is greater or equal to 1e+21, this method simply calls number.prototype.tostring() and returns a string in exponential notation.
Number.prototype.toPrecision() - JavaScript
if the precision argument is omitted, behaves as number.prototype.tostring().
Object.prototype.constructor - JavaScript
/ remains unchanged new date(), new error(), new function(), function () {}, math, new number(), 1, // remains unchanged new object(), {}, new regexp(), /(?:)/, new string(), 'test' // remains unchanged ] for (let i = 0; i < types.length; i++) { types[i].constructor = type types[i] = [types[i].constructor, types[i] instanceof type, types[i].tostring()] } console.log(types.join('\n')) this example displays the following output (comments added for reference): function type() {},false, // new array() function type() {},false, // [] function type() {},false,false // new boolean() function boolean() { [native code] },false,true ...
Object.keys() - JavaScript
polyfill to add compatible object.keys support in older environments that do not natively support it, copy the following snippet: // from /docs/web/javascript/reference/global_objects/object/keys if (!object.keys) { object.keys = (function() { 'use strict'; var hasownproperty = object.prototype.hasownproperty, hasdontenumbug = !({ tostring: null }).propertyisenumerable('tostring'), dontenums = [ 'tostring', 'tolocalestring', 'valueof', 'hasownproperty', 'isprototypeof', 'propertyisenumerable', 'constructor' ], dontenumslength = dontenums.length; return function(obj) { if (typeof obj !== 'function' && (typeof obj !== 'object' || ...
Object.prototype.toLocaleString() - JavaScript
description object's tolocalestring returns the result of calling tostring().
Reflect.has() - JavaScript
examples using reflect.has() reflect.has({x: 0}, 'x') // true reflect.has({x: 0}, 'y') // false // returns true for properties in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler method obj = new proxy({}, { has(t, k) { return k.startswith('door') } }); reflect.has(obj, 'doorbell') // true reflect.has(obj, 'dormitory') // false reflect.has returns true for any inherited properties, like the in operator: const a = {foo: 123} const b = {__proto__: a} const c = {__proto__: b} // the prototype chain is: c -> b -> a reflect.has(c, 'foo')...
RegExp.prototype.flags - JavaScript
polyfill if (regexp.prototype.flags === undefined) { object.defineproperty(regexp.prototype, 'flags', { configurable: true, get: function() { return this.tostring().match(/[gimsuy]*$/)[0]; } }); } examples using flags /foo/ig.flags; // "gi" /bar/myu.flags; // "muy" specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.flags' in that specification.
String.prototype.codePointAt() - JavaScript
e, 'writable': true }); } else { string.prototype.codepointat = codepointat; } }()); } examples using codepointat() 'abc'.codepointat(1) // 66 '\ud800\udc00'.codepointat(0) // 65536 'xyz'.codepointat(42) // undefined looping with codepointat() for (let codepoint of '\ud83d\udc0e\ud83d\udc71\u2764') { console.log(codepoint.codepointat(0).tostring(16)) } // '1f40e', '1f471', '2764' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.codepointat' in that specification.
String.prototype.normalize() - JavaScript
"\u00f1": let string1 = '\u00f1'; // ñ let string2 = '\u006e\u0303'; // ñ string1 = string1.normalize('nfc'); string2 = string2.normalize('nfc'); console.log(string1 === string2); // true console.log(string1.length); // 1 console.log(string2.length); // 1 console.log(string2.codepointat(0).tostring(16)); // f1 compatibility normalization in unicode, two sequences of code points are compatible if they represent the same abstract characters, and should be treated alike in some — but not necessarily all — applications.
String.prototype.padStart() - JavaScript
examples basic examples 'abc'.padstart(10); // " abc" 'abc'.padstart(10, "foo"); // "foofoofabc" 'abc'.padstart(6,"123465"); // "123abc" 'abc'.padstart(8, "0"); // "00000abc" 'abc'.padstart(1); // "abc" fixed width string number conversion // javascript version of: (unsigned) // printf "%0*d" width num function leftfillnum(num, targetlength) { return num.tostring().padstart(targetlength, 0); } const num = 123; console.log(leftfillnum(num, 5)); // expected output: "00123" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.padstart' in that specification.
String.prototype.repeat() - JavaScript
log(2)); while (count) { str += str; count--; } str += str.substring(0, maxcount - str.length); return str; } } examples using repeat 'abc'.repeat(-1) // rangeerror 'abc'.repeat(0) // '' 'abc'.repeat(1) // 'abc' 'abc'.repeat(2) // 'abcabc' 'abc'.repeat(3.5) // 'abcabcabc' (count will be converted to integer) 'abc'.repeat(1/0) // rangeerror ({ tostring: () => 'abc', repeat: string.prototype.repeat }).repeat(2) // 'abcabc' (repeat() is a generic method) specifications specification ecmascript (ecma-262)the definition of 'string.prototype.repeat' in that specification.
String.prototype.toUpperCase() - JavaScript
examples basic usage console.log('alphabet'.touppercase()); // 'alphabet' conversion of non-string this values to strings this method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = string.prototype.touppercase.call({ tostring: function tostring() { return 'abcdef'; } }); const b = string.prototype.touppercase.call(true); // prints out 'abcdef true'.
String.prototype.valueOf() - JavaScript
this value is equivalent to string.prototype.tostring().
Symbol.for() - JavaScript
examples using symbol.for symbol.for('foo'); // create a new global symbol symbol.for('foo'); // retrieve the already created symbol // same global symbol, but not locally symbol.for('bar') === symbol.for('bar'); // true symbol('bar') === symbol('bar'); // false // the key is also used as the description var sym = symbol.for('mario'); sym.tostring(); // "symbol(mario)" to avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols: symbol.for('mdn.foo'); symbol.for('mdn.bar'); specifications specification ecmascript (ecma-262)the definition of 'symbol.for' in that specification.
WebAssembly.CompileError - JavaScript
webassembly.compileerror.prototype.tostring() returns a string representing the specified error object..
WebAssembly.Global - JavaScript
global.prototype[@@tostringtag] the initial value of the @@tostringtag property is the string value "webassembly.global".
WebAssembly.LinkError - JavaScript
webassembly.linkerror.prototype.tostring() returns a string representing the specified error object..
WebAssembly.RuntimeError - JavaScript
webassembly.runtimeerror.prototype.tostring() returns a string representing the specified error object..
isNaN() - JavaScript
"37.37" is converted to the number 37.37 which is not nan isnan("37,5"); // true isnan('123abc'); // true: parseint("123abc") is 123 but number("123abc") is nan isnan(''); // false: the empty string is converted to 0 which is not nan isnan(' '); // false: a string with spaces is converted to 0 which is not nan // dates isnan(new date()); // false isnan(new date().tostring()); // true // this is a false positive and the reason why isnan is not entirely reliable isnan('blabla'); // true: "blabla" is converted to a number.
in operator - JavaScript
(if you want to check for only non-inherited properties, use object.prototype.hasownproperty() instead.) 'tostring' in {} // returns true specifications specification ecmascript (ecma-262)the definition of 'relational operators' in that specification.
this - JavaScript
function bar() { console.log(object.prototype.tostring.call(this)); } bar.call(7); // [object number] bar.call('foo'); // [object string] bar.call(undefined); // [object global] the bind method ecmascript 5 introduced function.prototype.bind().
for...in - JavaScript
objects created from built–in constructors like array and object have inherited non–enumerable properties from object.prototype and string.prototype, such as string's indexof() method or object's tostring() method.
throw - JavaScript
*/ function zipcode(zip) { zip = new string(zip); pattern = /[0-9]{5}([- ]?[0-9]{4})?/; if (pattern.test(zip)) { // zip code value will be the first match in the string this.value = zip.match(pattern)[0]; this.valueof = function() { return this.value }; this.tostring = function() { return string(this.value) }; } else { throw new zipcodeformatexception(zip); } } function zipcodeformatexception(value) { this.value = value; this.message = 'does not conform to the expected format for a zip code'; this.tostring = function() { return this.value + this.message; }; } /* * this could be in a script that validates address...
pointer-events - SVG: Scalable Vector Graphics
ect itself --> <rect x="10" y="0" height="10" width="10" fill="black" /> <circle cx="15" cy="5" r="4" fill="white" pointer-events="none" /> </svg> window.addeventlistener('mouseup', (e) => { // let's pick a random color between #000000 and #ffffff const color = math.round(math.random() * 0xffffff) // let's format the color to fit css requirements const fill = '#' + color.tostring(16).padstart(6,'0') // let's apply our color in the // element we actually clicked on e.target.style.fill = fill }) as a presentation attribute, it can be applied to any element but it is mostly relevant only on the following twenty-three elements: <a>, <circle>, <clippath>, <defs>, <ellipse>, <foreignobject>, <g>, <image>, <line>, <marker>, <mask>, <path>, <pattern>, <polygon>, <polyl...
<script> - SVG: Scalable Vector Graphics
WebSVGElementscript
ncies, like it uses the href attribute instead of src and it doesn't support ecmascript modules so far (see browser compatibility below for details) html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <script> // <![cdata[ window.addeventlistener('domcontentloaded', () => { function getcolor () { const r = math.round(math.random() * 255).tostring(16).padstart(2,'0') const g = math.round(math.random() * 255).tostring(16).padstart(2,'0') const b = math.round(math.random() * 255).tostring(16).padstart(2,'0') return `#${r}${g}${b}` } document.queryselector('circle').addeventlistener('click', (e) => { e.target.style.fill = getcolor() }) }) // ]]> </script> <circle cx="5" cy="5" r="4" /> </svg> ...