Jason
Jason

Reputation: 603

Remove certain characters in JavaScript string?

Let's say I have a string: http://www.foo.com/#bar

How would I go about removing everything before, and including, # so I'm only left with bar?

Upvotes: 0

Views: 543

Answers (3)

user748221
user748221

Reputation:

IF the location was LOADED you can do:

window.location.hash.slice(1)

window.location is an object with a bunch of useful stuff in it like the current security mode (http/s, domain, subdomain, etc.). The hash property contains everything starting with #. Slice is a method of both String and Array, allowing your to start at X and optionally end at Y. (so slice(1) is the same as "start after first and go until the end).

However, the hash property will not show what was typed into the location bar before a pageload. The location property of window refers to load location of the document, not the arbitrary things typed into the browser bar without the user submitting them.

Upvotes: 1

James Andino
James Andino

Reputation: 25789

If you just want to get the hash from the URL location.hash will return it.( It is possible to have a URL with more then one #)
http://www.w3schools.com/jsref/prop_loc_hash.asp

Upvotes: 0

Headshota
Headshota

Reputation: 21449

you can use split:

var myBar = "http://www.foo.com/#bar".split("#")[1];

Upvotes: 2

Related Questions