I am dealing with the following collection of strings
http://example.com
https://example.com
http://www.example.com
Is there a way to remove the http://
or https://
prefixes from these URLs?
I am dealing with the following collection of strings
http://example.com
https://example.com
http://www.example.com
Is there a way to remove the http://
or https://
prefixes from these URLs?
Here's a suggestion for you:
const website = "https://example.com";
const websiteNoProtocol = website.replace(/^https?\:\/\//i, "");
One way to utilize the URL object is by following this method:
const urlWithoutProtocol = new URL(url).host;
An alternative method is to utilize the URL() constructor, which simplifies the parsing of URL strings and eliminates the need for complex regex patterns:
let u = new URL('https://www.facebook.com/companypage/');
URL {
hash: ""
host: "www.facebook.com"
hostname: "www.facebook.com"
href: "https://www.facebook.com/companypage/"
origin: "https://www.facebook.com"
password: ""
pathname: "/companypage/"
port: ""
protocol: "https:"
search: ""
searchParams: URLSearchParams {}
username: ""
}
u.host // www.facebook.com
u.hostname // www.facebook.com
While URL()
does remove the protocol, it retains the 'www' subdomain. If you also wish to eliminate the subdomain, you can achieve this by using the .replace()
function:
u.host.replace(/^www./, '') // www.facebook.com => facebook.com
let link="https://website.com";
link=/^http(s)?:\/\/(.+)$/i.exec(link);
link=link[2];
If you want to parse links without the http/https, you can use this:
let link="https://website.com";
link=/^(http(s)?:\/\/)?(.+)$/i.exec(link);
link=link[3];
let link = "https://website.com";
link = link.substr( link.indexOf(':') + 3 );
Instead of using .substr()
, you can also opt for .slice()
or .substring()
. All these methods will yield the same output in this scenario.
link = link.slice( link.indexOf(':') + 3 );
link = link.substring( link.indexOf(':') + 3 );
UPDATE: It seems that the question requirements have been altered based on a comment under another response.
If there might not be a http://
in the string, then follow these steps:
let link = "website.com";
let index = link.indexOf('://');
if( index > -1 )
link = link.substr( index + 3 );
This response builds upon previous answers, utilizing http://
, https://
, or //
which are commonly used.
I am grateful for the insights shared in the earlier responses that guided me to this solution!
const urls = [ "http://example.com", "https://example.com", "//example.com" ]
// The regular expression below indicates: replace `//` or replace `//` along with any additional content
const resolveHostNames = urls.map(url => url.replace(/\/\/|.+\/\//, ''))
console.log(resolveHostNames);
Feel free to access a link to a codepen for reference.
Remove the protocol section from a URL:
const website = "https://example.com";
const urlNoProtocol = website.split('/').slice(2).join('/');
This code snippet is designed to work with various protocols such as ftp, http, gopher, nntp, telnet, wais, file, and prospero, as outlined in RFC 1738. However, it does not support protocols like mailto and news that do not contain '//.'
It is important to understand that the use of inherited protocol //
in real web pages is a common practice as mentioned by Paul Irish.
For this reason, I recommend using a regular expression that accounts for this scenario:
/^\/\/|^https?:\/\//
(you can optimize it further)
A more effective approach,
url.replace(/(^(\w+:)?\/\//, '')
If there aren't any double slashes except for the protocol, here's a way to achieve the desired result:
let link = "https://example.com";
let withoutProtocol = link.split('//')[1];
To utilize the HTMLHyperlinkElementUtils from DOM, you can implement the following function:
function excludeProtocol(link) {
const anchor = document.createElement('a');
anchor.href = link;
// If the original URL is relative, the new href will be absolute.
return anchor.href.replace(anchor.protocol + '//', '');
}
excludeProtocol('https://testsite.com/hyperlink');
// 'testsite.com/hyperlink'
excludeProtocol('error://broken_link/a');
// 'broken_link/a'
Refer to HTMLHyperlinkElementUtils on MDN:
anchor.hostname
, testsite.com
anchor.host
, testsite.com:3000
anchor.pathname
, /hyperlink/page.html
anchor.search
, ?x=1&y=2
anchor.hash
, #bar
anchor.username
, anchor.password
, anchor.port
, and more.
When you have a simple task like extracting the protocol from a URL, using regex can be unnecessary because there's a convenient built-in URL
interface that can do it in just 2 lines of code:
let url = "https://stackoverflow.com/questions/3999764/taking-off-the-http-or-https-off-a-javascript-string";
let a = new URL(url);
let withoutProtocol = a.host+a.pathname;
console.log(`Without protocol: ${withoutProtocol}`);
console.log(`With protocol: ${url}`);
The split function in Javascript comes to the rescue once again! Incredible!!!
var link = "https://test.com";
link = link.split("://")[1]; // for https websites use link..split("://")[0];
console.log(link);
After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...
It is my belief that by utilizing var express = require('express');, the variable express receives a function reference of createApplication(). So, when we invoke express(), it will yield an app object. However, my question is, if var express is ...
I'm attempting to modify the Highcharts tooltip for a stacked column chart in order to have the arrow on the tooltip point to the center of the bar. I understand that I can utilize the positioner callback to adjust the tooltip's position, but it ...
When the window is resized, I want to display a collapsed 'More options' button that will collapse all hidden <li> elements. Here is an example: <li id="menu_more_container" class="dropdown" style="display: none; ...
Currently, I am experimenting with d3 animations using d3.transitions specifically involving circles. Consider the circle animation example below (d3.transition()): animationTime = 500; svg = d3.select('#svg'); // Locate th ...
Trying to extract specific text from a website in Chrome's developer console. For example, here is the code snippet: <div class="someClass">This is some text!</div> Expected it to work with this command, but it returns 'undefined&a ...
I'm facing an issue while trying to set up a basic Vue JS application on my local machine, utilizing the materialize-css navbar (). Upon running the app in the terminal, the following error message is displayed. Unable to locate the specified module: ...
I have set up an icecast server on my system, and the clients connecting to it will be embedded in web pages using either HTML5 or Flash. Currently, I am utilizing audio.js with a flash fallback for this purpose. The issue at hand is that the audio and a ...
On my website, I have a <p> tag and I am interested in knowing which JavaScript function is responsible for adding text inside this element. Is there a special method in Chrome to add a listener on this tag and pinpoint the script that writes to it ...
I have an HTML table connected with a component field gameArray and I need it to: Show 'H' when the user's cursor hovers over TD (:hover) and the corresponding field in gameArray is an empty string, Fill the gameArray field after a click. ...
When I attempted to run the command npx create-react-app my-app, I encountered an error: (ps: I also tried running npm init and npm install create-react-app before executing the aforementioned command, but still got the same error.) HELP! Installing pack ...
Hey there, I'm new to scripting and I've run into a problem. I'm trying to figure out how to load a page in a parent div when clicking buttons in a child div. Specifically, I want to load a specific page in the parent div. Just to clarify, t ...
My objective is to launch a popup containing an input field and automatically bring focus to that input. I have attempted using $('#input').focus(), $('#input').first().focus(), and $('#input')[0].focus(), but unfortunately, ...
In my current project, I am utilizing ng-repeat to display objects in rows. To achieve my desired functionality of only displaying elements present in the DOM, I decided to use a helpful plugin called angular-vs-repeat. However, I am facing an issue with u ...
I have recently started working with Angular.js and I am attempting to create a custom directive with a controller containing functions that is connected to another controller. I want the object in the main controller ($scope.MyObj) to update in sync wit ...
I am struggling to retrieve the user inputs from text fields within a dialog window in order to utilize them for a SQL query. The issue I am encountering is that I am unable to effectively use the array in PHP. Despite no error messages being displayed, I ...
I am new to Angular and recently started learning how to manage state centrally using ngRx. However, I am facing a challenge as I have never used an Observable before. In my code, I have a cart that holds an array of objects. My goal is to iterate over the ...
After designing a Navigation menu component for desktop mode, I also created a separate side drawer component to handle variations in screen size. However, a friend of mine advised that a side drawer menu component may not be necessary. According to them ...
I am encountering an issue with my current POST request. There is a simple function in place that handles the sending of data to the server using AJAX. handleSubmit(event) { var http = new XMLHttpRequest(); // object allows for making http requests // ...
Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...