0

I have a url something like that:

//my-url-adresses.com/web/Assets/js/javascripts?v=5.2&marker=2017-05/logo_30dKmOHPNLq8CfiOYfqhmarkerv2.png&cdn=//cdn.mywebsite.com/files/

and I want to get this part: (after cdn=):

//cdn.mywebsite.com/files/

I have provided my code below. Please correct where i am wrong. Thanks in advance.

var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
var scripturl = myScript.src;
var cdnUrl = getParameterByName("cdn", scripturl);
var markerUrl = getParameterByName("marker", scripturl);


function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


console.log(markerUrl);
<script id="scripts" src="//my-url-adresses.com/web/Assets/js/javascripts?v=5.2&amp;marker=2017-05/logo_30dKmOHPNLq8CfiOYfqhmarkerv2.png&amp;cdn=//cdn.mywebsite.com.com/files/" defer></script>
ani_css
  • 2,118
  • 3
  • 30
  • 73

2 Answers2

2

I noticed that your code is not able to access the script url using the index property. I also noticed you have id in your script tag. It would be better to use that, otherwise if you have some script tag with some function in your page at the bottom of page, it would get those(since you are finding the last script tag in the page) and since it don't have src it won't fetch result.

Here is a solution using getElementById()

var myScript = document.getElementById('scripts');
var scripturl = myScript.src;
var cdnUrl = getParameterByName("cdn", scripturl);
var markerUrl = getParameterByName("marker", scripturl);


function getParameterByName(name, url) {
    url = decodeURIComponent(url);
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


console.log(markerUrl);
<script id="scripts" src="//my-url-adresses.com/web/Assets/js/javascripts?v=5.2&amp;marker=2017-05/logo_30dKmOHPNLq8CfiOYfqhmarkerv2.png&amp;cdn=//cdn.anitur.com/web/" defer></script>
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
1

Try this:

   var myScript = document.getElementById('scripts');
var scripturl = myScript.src; // or window.location.href for current url
    var captured = /cdn=([^&]+)/.exec(scripturl )[1];  
    var result = captured ? captured : 'myDefaultValue';
    console.log(result);
jANVI
  • 718
  • 3
  • 12