I have the following code:
<script>
document.write('<img src=//testURLaction?item=' + window.location.href + '>');
</script>
If the current window.location (url) contains http or https I would like to remove it.
Update: Is there a reason for the two vote downs? My question was clear
I have the following code:
<script>
document.write('<img src=//testURL.action?item=' + window.location.href + '>');
</script>
If the current window.location (url) contains http or https I would like to remove it.
Update: Is there a reason for the two vote downs? My question was clear
Share Improve this question edited Apr 19, 2017 at 14:39 Mariton asked Apr 18, 2017 at 21:03 MaritonMariton 6213 gold badges14 silver badges29 bronze badges 2-
window.location.href
returns full URL. Are you trying to remove more than only "http" or "https" fromwindow.location.href
? What is expected resulting string? – guest271314 Commented Apr 18, 2017 at 21:05 -
var withoutPrefix = window.location.href.toLowerCase().replace(/http:/g, "").replace(/https:/g, "");
- This will removehttp:
andhttps:
from your url using a simple.replace()
. – Tyler Roper Commented Apr 18, 2017 at 21:05
3 Answers
Reset to default 4To remove just http
/https
: window.location.href.replace(/^http(s?)/i, "");
To remove http:
/https:
: window.location.href.replace(/^http(s?):/i, "");
To remove http://
/https://
: window.location.href.replace(/^http(s?):\/\//i, "");
These are all case-insensitive and only remove from the start of the string
Simple regex would do the trick.
const removeHttps = input => input.replace(/^https?:\/\//, '');
const inputs = ['https://www.stackoverflow.', 'http://www.stackoverflow.'];
inputs.forEach(input => console.log('Input %s, Output %s', input, removeHttps(input)));
However, a cleaner approach might be to instead just bine ${document.location.host}${document.location.pathname}${document.location.search}
. It's longer, but you don't have to do any regex.
host
is something likestackoverflow.
pathname
is something like/questions
search
is something like?param=value
Together they give the whole URL without the protocol (which is document.location.protocol
, by the way).
If you want to only replace http
or https
, you should use window.location.href.replace(/http(s?)/, '');
as Kieran E suggested. If you want to always remove the protocol, you could use window.location.href.replace(window.location.protocol, '');
.