0

I have defined the following entry in my html:

script type="text/javascript" src="/dir/path/js/myApp.js?org=XYZ"></script>

Now i want to read the value "XYZ" as an input in myApp.js. How can i do this?

orbit
  • 1,228
  • 2
  • 13
  • 23
  • 1
    Duplicate of https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Adder Oct 11 '17 at 14:44

1 Answers1

1

You can use split or match or some other String methods to extract the part you want to get.

Example below (you can run the code):

// Assuming this is the url you get
var url = '/dir/path/js/myApp.js?org=XYZ';

// Split the url and get the second part
var query = url.split(/\?/)[1];

var value = query.split(/=/)[1];

console.log('Query: ' + query);
console.log('Intended value: ' + value);

In your example, you want to read from a <script></script> tag.

To do so, it is easier to first give the <script> an id:

<script id="example" src="/dir/path/js/myApp.js?org=XYZ"></script>

Then you get the src by:

document.getElementById('example').src

Then from here you can modify the code example above for your use.

PS

If you want to read from the URL instead, you can use window.location.href to read the URL as a string.

yqlim
  • 6,898
  • 3
  • 19
  • 43
  • I wonder if the mention of window.location.href at the start of your answer will confuse some who read this. Anyway, I give you an upvote, as the solution in the second half of your answer is spot on :) – athms Oct 11 '17 at 15:08
  • @athms you're right. I've restructured the paragraph order. – yqlim Oct 11 '17 at 15:34