如何使用javascript删除http或https
我有以下代码:如何使用javascript删除http或https,javascript,Javascript,我有以下代码: <script> document.write('<img src=//testURL.comaction?item=' + window.location.href + '>'); </script> 文件。写(“”); 如果当前window.location(url)包含http或https,我希望将其删除 更新: 两次投票失败有什么原因吗?我的问题很清楚只删除http/https:window.location.href.repla
<script>
document.write('<img src=//testURL.comaction?item=' + window.location.href + '>');
</script>
文件。写(“”);
如果当前window.location(url)包含http或https,我希望将其删除
更新:
两次投票失败有什么原因吗?我的问题很清楚只删除
http
/https
:window.location.href.replace(/^http(s?)/i,”)代码>
要删除http:
/https:
:window.location.href.replace(/^http(s?):/i,”)代码>
要删除http://
/https://
:window.location.href.replace(//^http(s?):\/\///i,”)代码>
这些都不区分大小写,仅从字符串开头删除。如果只想替换http
或https
,则应使用window.location.href.replace(/http(s?/,'')代码>如Kieran E所建议。如果要始终删除协议,可以使用window.location.href.replace(window.location.protocol')代码>简单的正则表达式就可以了
const removeHttps=input=>input.replace(/^https?:\/\/,“”);
常量输入=['https://www.stackoverflow.com', 'http://www.stackoverflow.com'];
inputs.forEach(input=>console.log('input%s,Output%s',input,removeHttps(input))
window.location.href
返回完整的URL。您是否试图从window.location.href
中删除的不仅仅是“http”或“https”?预期的结果字符串是什么?var withoutPrefix=window.location.href.toLowerCase().replace(/http:/g,“”)。replace(/https:/g,“”)
-这将使用一个简单的.replace()
从您的url中删除http:
和https:
。如果需要删除冒号,请尝试添加“i”修饰符以进行不区分大小写的匹配/http(s?)/i
@SteamDev很好!我还为Strings的开头添加了一个锚,感谢您提供的细节。真棒