user3218981
user3218981

Reputation: 1

How to pass a variable to javascript from html as part of url

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?

Upvotes: 0

Views: 96

Answers (1)

yqlim
yqlim

Reputation: 7080

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.

Upvotes: 1

Related Questions