How do I access or replicate string value of an object? - javascript

For example, I'm trying to isolate the first 5 characters of window.location.
var ltype, string = 'string';
console.log(window.location); // file:///C:/for example
console.log(typeof window.location); // [OBJECT]
lType=window.location.substr(0,5); // 'not a function' (quite so)
string=window.location;
lType=string.substr(0,5); // fails similarly
Q1: Can I somehow 'bind' substr() to window.location?
I can see that string=window.location replicates a reference and not
a value, so
Q2: How can a separate, discrete copy of a complex structure such as an object or an array be created [without using JSON.stringify() or JSON.parse() - which is what I am presently resorting to]?

try
string = window.location.href.toString();
instead of
string=window.location;
Because window.location will return object not a string.

window.location is an object, so you can't use string functions on it - as you've noticed. In order to get the actual location as a string (to perform string operations on it), you'll need to convert it to a string somehow.
window.location.href is a property provided by the object itself.
window.location.toString() is a method on all JavaScript objects, overridden here.
However, beware of the XY problem. It looks to me like you're trying to retrieve the protocol (the http: bit) of the URI. There's a property for that too - window.location.protocol.
lType = window.location.protocol;
You should use that - it's more robust (consider https:// or, worse, ftp://...).

Related

casting a string as a JavaScript object

In JavaScript, I can cast convert numbers to strings and vice versa, but there is no way to cast convert a string to an object
num = 1
str = '1'
num_as_str = String(num) // "1"
str_as_num = Number(str) // 1
str = '{ a: "foo", b: "bar", c: { a: "foo", b: "bar" }}'
str_as_obj = Object(str) // does not exist
Assuming my string (to be cast converted as an object) is predictable and relatively simply, what is the best way to achieve the above other than using a regexp to parse out the indiv key-val pairs? Suggestions welcome
background: I want to do the above because I want to be able to pass and receive complex values in a URL. For example, /index.html?q=within({r:20, u: "kms", lat: 35.32, lng: -22.0132}) (of course, I will URL encode/decode properly along the way). Fwiw, the node querystring module wipes out anything other strings, numbers, booleans and arrays by coercing them to empty strings.
background2: of course, I know about JSON.parse and JSON.stringify, but I have a user-submitted URL querystring param that is most easily transmitted as an object, except a querystring cannot deal with an object. That is what I am trying to find a way around.
I want to do the above because I want to be able to pass and receive complex values in a URL
Use JSON, not a JavaScript object initializer.
of course, I know about JSON.parse and JSON.stringify, but I have a user-submitted URL querystring param that is most easily transmitted as an object
The JSON version ({"a":"foo","b":"bar","c":{"a":"foo","b":"bar"}}) is just as easily transmitted. It URI-encodes to
%7B%22a%22%3A%22foo%22%2C%22b%22%3A%22bar%22%2C%22c%22%3A%7B%22a%22%3A%22foo%22%2C%22b%22%3A%22bar%22%7D%7D
vs. your original:
%7Ba%3A%22foo%22%2Cb%3A%22bar%22%2Cc%3A%7Ba%3A%22foo%22%2Cb%3A%22bar%22%7D%7D
Not much difference. (Yes, it's slightly longer.) And it has the advantage that JSON.parse is a built-in feature that doesn't allow arbitrary code execution.
If you must use the object literal string instead, you have to parse that string. There are two built-in ways to do it (eval and new Function), but unfortunately both of them execute the code, and don't limit what the code can be — you can't say, for instance, "only allow an object literal and no function calls."
It sounds like it's entirely possible that User A will be specifying the string and then you'll be evaluating it when showing a page to User B. If so, you can't use eval or new Function without exposing User B to risks from malicious code.
So you'll need to use a parser like Esprima or similar instead. You could probably also adapt Crockford's original JSON parser to allow unquoted property names.
So really, JSON is the way to go, but if you really don't want JSON, use a parser that doesn't allow arbitrary code execution.

How does String.length work in JavaScript?

I want to know how is the string length of a string calculated in js.
Is is a function call or a class data member.
I want to know what happens when we execute the following code :
a = 'this is a string';
console.log(a.length); // what actually happens at this point?
Also if a do this :
a += ' added something';
console.log(a.length); // at what point is the new length calculated
//and/or updated for the object 'a';
And at last, do I need to store the string length in a temp variable while using a loop over the string or can I directly use the following (which one is faster/processor efficient) :
for(var i=0;i<a.length;i++){
// doing anything here
}
Summing up my question, I want to know the processing behind String.length and which practice is better while looping over strings?
A string is immutable in JavaScript.
a += "somestring" doesn't change the length of a string but makes a new string.
This means there is no "new length", but the length is just part of the definition of the string (more precisely it is stored in the same structure in implementations).
Regarding
for(i=0;i<a.length;i++){ // did you forget the 'var' keyword ?
a not so uncommon practice (if you don't change a) was to optimize it as
for (var i=0, l=a.length; i<l; i++)
in order to avoid the reading of the length but if you compare the performances with modern engines, you'll see this doesn't make the code any faster now.
What you must remember : querying the length of a string is fast because there is no computation. What's a little less fast is building strings (for example with concatenation).
Strings are a primitive type. At least that's what the documentation says. But we can access the length of the string as if we are accessing the property of an object(with the dot notation). Which indicates it's an object, Right?
Turns out, whenever we make a call from the string primitive to some property using the dot notation (for example, say length), the Js engine will take this primitive string and wrap it into an equivalent wrapper object, which is a String object. And then, the .length on that String object returns the length.
Interesting thing to note here is, that when we do something like this, our string still stays the same primitive string during all of this. And a temporary object is created to make our string operation work. Once the required property is fetched, this temporary object is deleted from the memory.
Hope this gives some high level understanding.
I'm answering your first question.
I'm also curious about this puzzle so I did some search myself, ended up finding -
Based on String documentation from Mozilla:
String literals (denoted by double or single quotes) and strings
returned from String calls in a non-constructor context (i.e., without
using the new keyword) are primitive strings. JavaScript automatically
converts primitives to String objects, so that it's possible to use
String object methods for primitive strings. In contexts where a
method is to be invoked on a primitive string or a property lookup
occurs, JavaScript will automatically wrap the string primitive and
call the method or perform the property lookup.
So as I understand, when you use somestring.length, the primitive string will first be wrapped as a String object, and then since the object has its property length, so it's just a internal method call to access and return.

Passing RegExp objects between content scripts and main add-on script

I am having an issue whereby I create a RegExp object in a content script and pass it as part of an object back to the main script using self.port.emit().
Somewhere along the way it seems to lose its identity as a RegExp and also its toString abilities. The following returns false in the main script, but true in the content script:
Object.prototype.toString.call(regexp) == '[object RegExp]';
regexp instanceof RegExp;
Interestingly for Arrays passed in the same way the following is true:
Object.prototype.toString.call(array) == '[object Array]';
Am I missing something?
The Add-on SDK doesn't pass objects around when you send messages, only strings - it essentially calls JSON.stringify() on one side and then JSON.parse() on the other. The result is easy to predict:
console.log(JSON.stringify(new RegExp()));
This gives you "{}". In other words, JSON.stringify() treats "custom" objects as normal objects without any properties, object prototypes and such are ignored. What you get in your main code is a plain object, same as if you call new Object().
If you need to pass a regular expression to your main code - send regexp.source, create an actual regular expression on the other side. Sending actual objects around isn't possible.
What about if you just sent the regex pattern instead of the whole rexexp object? e.g. encodeURIComponent(regexp.source);

String passing from JavaScript to Qt/C++ object

I'm stuck on a QtWebKit bridge issue on Windows and I ran out of
options. I don't have access to the exact code used but its something like below.
C++
class MyObject : QWidget {
Q_OBJECT
public:
QString data() const;
void setData(QString);
Q_PROPERTY(QString data READ data WRITE setData)
};
/* ... */
MyObject myObject;
frame->addToJavaScriptWindowObject("myObject", &myObject);
JavaScript
function drop(e) {
var url = e.dataTransfer.getData('url');
//alert(url); // Displays url correctly
myObject.data = url; // Assigns url to C++ object myObject
}
The alert box correctly displays the string value, e.g. 10.10.0.1.
The parameter on setData gives me the string "1". If I then view then memory at that address, I see the full url in memory (formatted as UTF-32 (4 bytes per character)), but whatever I try (toStdString, toAscii, utf16 - just to get sensible data) I do not seem to be able to get/use the whole string.
I event thought that maybe the debugger is playing a trick on me, so I pass the data to the method that actually needs this data (which also used a QString) it all might work - but sadly no.
Even if I make MyObject::setData Q_INVOKABLE and call setData directly I get the same
behaviour:
myObject.setData(url); // Assigns url to C++ object myObject
If I just pass the data as literal, all DOES work correctly, like
myObject.setData('10.10.0.1');
or
myObject.data = '10.10.0.1';
I do not understand why passing a literal works but a variable not, the 'url' variable should be a string type.
I'm partly there. String passing works as expected. However, the C++ object is embedded on a webpage and wraps an ActiveX (ActiveQt) object.
For this, I've seen some pages where you create a class that inherits from a QWebPage. There you have a createPlugins method that asks the QUiLoader to construct the widget for you (alternatively you use the Qt Metatype system). And my C++ object is registered.
When I use this custom WebPage on my WebView (using setPage), the strings are passed in wrongly. When I disable calling setPage, the strings passed correctly.
So string passing works (in some conditions).
I've created a new issue for this: Qt Webkit bridge ActiveQt string

How to get Javascript Objects from JavaScriptSerializer?

When I use the System.Web.Script.Serialization.JavaScriptSerializer.Serialize method, I get back valid JSON code.
This is usually perfect, but sometimes I want to get back the result as a Javascript object, not JSON. The Serialize method has an overload that takes a SerializationFormat parameter. That looks perfect... but it is marked as internal!
How can I get out a string of Javascript from the Serializer?
Take a look at the JScript DLL Eval object's JScriptEvaluate method (http://msdn.microsoft.com/en-us/library/microsoft.jscript.eval.jscriptevaluate.aspx):
using Microsoft.JScript;
var MyJSObject = Eval.JScriptEvaluate("{a:'Property1',b:'Property2'}", Engine);

Categories

Resources