Expand my Community achievements bar.

SOLVED

Getting hash (#) value from URL for data element

Avatar

Level 3

Hi there,

I am using DTM and I wanted to create a data element using the hash (#) value from an url.

If the url is testpages.com/#id=123 I would like to geht the "123" as value for my data element.

I tried window.location.hash.substring but it does not work. Can anybody help me with that? Any other ideas how to solve this problem?

Thank you very much.

Best Florian

1 Accepted Solution

Avatar

Correct answer by
Level 3

Hi guys,

thank you for your great support. I made a mistake. I tried to put to code directly into the js object field. But then I put the code into the custom script editor. It looks like this now:

return document.URL.substr(document.URL.indexOf('#')+4); 

And it works :-)

Thanks a lot.

Best Florian

View solution in original post

5 Replies

Avatar

Level 10

Hi Florian,

Do you have URL where we can test this?

I'm not a developer, but it looks like the code below might get you what you'd like. Try plugging this into the console on the page to see if it returns the correct value.

document.URL.substr(document.URL.indexOf('#')+4)

If it does, you can put the code it in a data element and see if _satellite.getVar('data_element_name') returns the expected value.

Thanks,
Jantzen

Avatar

Level 3

Hi Jantzen,

thank you for your quick response. Unfortunatelly it does not work. If I put your code in the data element I only get the default value.

If I use location.hash it works perfectly well but then I get  whole anchor part of the URL, including the hash sign (#) :-/

Any other ideas?

Thank you.

Florian

Avatar

Employee Advisor

Hi Florian,

Can you give a general structure of the URL?

Would you have other parameters apart form id after #?

I am talking your URL to be www.abc.com/path/#id=123

You can run the following function:

function id(){

  var x = document.URL.substr(document.URL.indexOf('#')+1);

  return x.substr(x.indexOf('=')+1);

  return y;

}

You can also run a single line of function:

document.URL.substr(document.URL.indexOf('#')+1).substr(document.URL.substr(document.URL.indexOf('#')+1).indexOf('=')+1);

Hope this helps.

-Hyder

Avatar

Correct answer by
Level 3

Hi guys,

thank you for your great support. I made a mistake. I tried to put to code directly into the js object field. But then I put the code into the custom script editor. It looks like this now:

return document.URL.substr(document.URL.indexOf('#')+4); 

And it works :-)

Thanks a lot.

Best Florian

Avatar

Level 1

check this package to solve every problem related hash called react-hash-control

it allow use read params as hash also allow to get entire hash history and many more just install it by following command and for documentation check react-hash-control

npm install react-hash-control