使用 Javascript / Jquery 重写 URL 前缀



我正在使用javascript从外部API检索一些数据,然后在HTML页面上显示这些数据。

在此返回的数据中是一个 URL,它采用以下格式;

var url = https://img.evbuc.com/moreStuff

我需要重写这个 URL,使其以 www 为前缀,就像这样;

var url = https://www.img.evbuc.com/moreStuff

我想使用javascript或jquery来实现这一点。

我怎样才能做到这一点?正确代码的解释也很棒。

你不需要

正则表达式,你可以简单地使用 URL API

let url = "https://img.evbuc.com/moreStuff"
let parsed = new URL(url)
parsed.host = parsed.host.startsWith('www.') ? parsed.host : "www."+ parsed.host
console.log(parsed)

您可以使用正则表达式进行搜索和替换。

以下示例也适用于:

  • http://img.evbuc.com/moreStuff
  • //img.evbuc.com/moreStuff
  • https://img.evbuc.com/moreStuff//someMoreStuff

function prependUrl(url) {
  return url.replace(/^([^/]*)(//)(.*)/, '$1//www.$3');
}
const urls = [
    'https://img.evbuc.com/moreStuff',
    'http://img.evbuc.com/moreStuff',
    '//img.evbuc.com/moreStuff',
    'https://img.evbuc.com/moreStuff//someMoreStuff'
];
urls.forEach((url) => console.log(`${ url } -> ${ prependUrl(url) }`));

  • 正则表达式包含 3 个捕获组:

    1. 选择第一个/之前的所有内容(不包括(
    2. 选择//(对于协议根(
    3. 选择其余部分
  • 替换值将所有内容都带到第一个/(也可能是空字符串(

  • //替换为//www.
  • 附加其余部分

如果你想要一些可以与任何协议一起使用的东西,试试这个正则表达式:

var url = "https://img.evbuc.com/moreStuff"
var new_url = url.replace(/^([a-zA-Z][a-zA-Z0-9.+-]*):///, "$1://www.")
console.log('new URL: ', new_url)

简单的字符串操作:

var url = 'https://img.evbuc.com/moreStuff'
var newUrl = url.split('//')[0] + '//www.' + url.split('//')[1]
console.log(newUrl)

另一种方法是这样的:

var url = 'https://img.evbuc.com/moreStuff'
var newUrl = url.replace('https://', 'https://www.')
console.log(newUrl)

最新更新