最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I remove http or https using javascript - Stack Overflow

programmeradmin0浏览0评论

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" from window.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 remove http: and https: from your url using a simple .replace(). – Tyler Roper Commented Apr 18, 2017 at 21:05
Add a ment  | 

3 Answers 3

Reset to default 4

To 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 like stackoverflow.
  • 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, '');.

发布评论

评论列表(0)

  1. 暂无评论