使用 JavaScript 从 URL 中删除 http 或 https
要从 url 中删除 http://
或 https://
,请使用以下正则表达式调用 replace()
方法 - /^https?:\/\//
和一个空字符串作为参数。 replace
方法将返回一个新字符串,其中 http://
部分已被删除。
function removeHttp(url) {
return url.replace(/^https?:\/\//, '');
}
// 👇️ "example.com"
console.log(removeHttp('https://example.com'));
// 👇️ "example.com"
console.log(removeHttp('http://example.com'));
如果我们希望避免使用正则表达式,请向下滚动到下一个副标题。
我们创建了一个可重用的函数,用于删除 url 的 http://
或 https://
部分。
我们将以下 2 个参数传递给 String.replace
方法:
- 我们要在字符串中匹配的正则表达式
- 每场比赛的替换
正斜杠
//
标记正则表达式的开始和结束。
插入符号 ^
匹配输入的开头,换句话说,字符串必须以 http(s)
开头。
问号 ?
与前面的项目匹配 0 次或 1 次。在示例中,问号使 s 字符可选。
最后,我们必须使用反斜杠转义正斜杠。
如果您在阅读正则表达式时需要帮助,请查看来自 MDN 的正则表达式速查表。
我们传递给 replace() 方法的第二个参数是正则表达式匹配的替换。出于我们的目的 - 一个空字符串,因为我们想删除 http:// 部分。
如果想避免使用正则表达式,请改用 String.startsWith
方法。
使用 startsWith 从 URL 中删除 'http://' 或 'https://'
要从 url 中删除 http://
或 https://
,请检查 url 是否以 https://
或 http://
开头,如果是,请使用 slice()
方法获取 url 之后的部分http协议。 slice()
方法返回一个代表原始字符串一部分的新字符串。
function removeHttp(url) {
if (url.startsWith('https://')) {
const https = 'https://';
return url.slice(https.length);
}
if (url.startsWith('http://')) {
const http = 'http://';
return url.slice(http.length);
}
return url;
}
// 👇️ "example.com/books"
console.log(removeHttp('https://example.com/books'));
// 👇️ "example.com"
console.log(removeHttp('http://example.com'));
我们首先检查 url 是否以 https://
开头,如果是我们使用 String.slice()
方法获取协议之后的 url 片段。
我们传递给 slice()
方法的唯一参数是起始索引——要包含在字符串中的第一个字符的索引。
// 👇️ "example.com"
console.log('http://example.com'.slice(7));
我们使用 http://
或 https://
字符串的长度来确定起始索引,这样我们就可以避免对幻数进行硬编码。
如果 url 不是以 http://
或 https://
开头,我们将按原样返回字符串。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。