我有一个类似的网址:
// my-url-adresses.com/web/Assets/js/javascripts?v=5.2&marker=2017-05/logo_30dKmOHPNLq8CfiOYfqhmarkerv2.png&cdn=//cdn.mywebsite.com/files/
我希望得到这个部分:(在cdn =之后):
// cdn.mywebsite.com/files /
我在下面提供了我的代码。请纠正我错在哪里。提前谢谢。
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&marker=2017-05/logo_30dKmOHPNLq8CfiOYfqhmarkerv2.png&cdn=//cdn.mywebsite.com.com/files/" defer></script>
答案 0 :(得分:1)
试试这个:
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);
答案 1 :(得分:1)
我注意到您的代码无法使用index属性访问脚本网址。我还注意到你的脚本标签中有id。最好使用它,否则如果你在页面底部的页面中有一些带有某些功能的脚本标签,它就会得到那些(因为你在页面中找到了最后一个脚本标签),因为它没有&#39 ; t src
它不会获取结果。
以下是使用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);
&#13;
<script id="scripts" src="//my-url-adresses.com/web/Assets/js/javascripts?v=5.2&marker=2017-05/logo_30dKmOHPNLq8CfiOYfqhmarkerv2.png&cdn=//cdn.anitur.com/web/" defer></script>
&#13;