Using web page address to create src for image on page

65 Views Asked by At

e.g. I have a file named: /SW1A2AA.htm

In the HTML I need to show the following image with the source for the image to include the filename (without the extension). I.e.:

<img src= "https://maps.googleapis.com/maps/api/staticmap?center=sw1a2aa&zoom=18&size=640x480">

Obviously if I need to do this for lots of pages, it would be easier if there was a way to amend the search string to depend on the filename (without the extension).

Please tell me there is a simple way to produce that result!

Thanks

1

There are 1 best solutions below

2
On BEST ANSWER

Here is my solution for your example (SW1A2AA.htm). Empty src attribute is not valid, so we use //:00 - you can read more about this solution here.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
</head>
<body>

<img id="map" src="//:0">


<script>
// grab the URL. I'm working locally so in my case it is /C:/Users/myLogin/Desktop/SW1A2AA.htm
var pageURL = window.location.pathname; 

// find the last position of the "/"
var fileNamePosition = pageURL.lastIndexOf("/"); 
// take file name and delete last 4 characters (SW1A2AA.htm -> SW1A2AA)
var fileName = pageURL.slice(fileNamePosition+1,-4);
// create src
var mapSrc = "https://maps.googleapis.com/maps/api/staticmap?center=" + fileName + "&zoom=18&size=640x480"; 

// update map src attribute
var map = document.getElementById("map");
map.setAttribute("src", mapSrc);


</script>
</body>
</html>