0
http://www.somewebsite.com/somepage/someotherpage#somesection

I'm trying to convert a given URL from window.location.href to a string and extract part of it to a variable using regex. '/(\#.*)/g'

The URLs all contain a # and all I basically want to do is dynamically store the characters that come after the hash, whether or not it includes the hash.

So far my attempts haven't worked:

var pageSection = window.location.href;
    newSection = pageSection.match('/(\#.*)/g');
console.log(newSection);

just returns null. My other attempts have just returned the whole URL.

Thanks in advance.

B_A_W
  • 86
  • 2
  • 9
  • Try `pageSection.match(/#.*/g)`. See http://stackoverflow.com/questions/2845913/javascript-simple-regexp-doesnt-work: *make it a regular expresison, not a string*. – Wiktor Stribiżew Jan 27 '17 at 12:42
  • Why not just use `window.location.hash.substring(1);` If you use `.hash` on `window.location` it will return `#somesection` so `substring(1)` will remove the `#` from the returned string giving you the hash value only. – NewToJS Jan 27 '17 at 12:48
  • That didn't work Wiktor – B_A_W Jan 27 '17 at 12:48
  • @NewToJS Thank you! That worked a treat! – B_A_W Jan 27 '17 at 12:56
  • @Lanlé a tip for next time. Just `console.log()` the object and you can see what properties that object has. Example `console.log(window.location)` will show you. `search` - `pathname` - `href` - `hostname` ect... – NewToJS Jan 27 '17 at 12:59

0 Answers0