0

I thought this would be much easier but obviously I missing something.

I have a reference to a javascript file in my html e.g.

<script src="myfile.js?k=123456"></script>

With typescript I want to pull the k query string value and use it when processing in my typescript/javascript. How can I do this?

amateur
  • 41,925
  • 62
  • 185
  • 308
  • Does this answer your question? [How do I get query string value from script path?](https://stackoverflow.com/questions/4716612/how-do-i-get-query-string-value-from-script-path) – evolutionxbox Mar 24 '20 at 12:17
  • did you try to put this code https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript into your myfle.js – bill.gates Mar 24 '20 at 12:26

2 Answers2

1

If you support modern browsers, then you can use URL.searchParams to parse out the k parameter like:

const src = document.body.querySelector('script').src;
const params = (new URL(src)).searchParams;
console.log(params.get('k'))
<script src="myfile.js?k=123456"></script>
palaѕн
  • 68,816
  • 17
  • 108
  • 129
0

You can use document.querySelector(), or add an id to your script tag, and get the query string value from its src property:

let value = document.querySelectorAll('script')[1].src.split('k=')[1];
let value2 = document.getElementById('script').src.split('k=')[1];

console.log(value, value2);
<script id="script" src="myfile.js?k=123456"></script>
Tamas Szoke
  • 4,679
  • 3
  • 23
  • 34