0

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]?

Ashrith Sheshan
  • 654
  • 4
  • 17
Bad Loser
  • 3,065
  • 1
  • 19
  • 31

2 Answers2

2

try

string = window.location.href.toString();

instead of

string=window.location;

Because window.location will return object not a string.

commit
  • 4,777
  • 15
  • 43
  • 70
  • Quite right: I had tried to to list the properies of the object using the famous old 'showProps' exec from XUL School. For some reason it gave no result when used against window.location. – Bad Loser Jun 28 '13 at 07:23
1

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://...).

Community
  • 1
  • 1
  • And when I accept your answer it seems to unaccept the previous answer. ??? I better go read the manual again – Bad Loser Jun 28 '13 at 07:31
  • @MattArnold `1` That's a separate question (that, furthermore, [has already been asked](http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object)). `2` There can be only one accepted answer. (Mine? Pretty please?) – michaelb958--GoFundMonica Jun 28 '13 at 07:32
  • I've read the manual, seen the light, leaving the green tick with you – Bad Loser Jun 28 '13 at 08:00