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?

2

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.