仅在javascript中使用正则表达式保留地址的结尾

仅在javascript中使用正则表达式保留地址的结尾,javascript,jquery,regex,Javascript,Jquery,Regex,我想保留url的开头,删除其余部分以显示源代码。我所做的是给我这样一个源代码:https:domainundefined/test1/test2.html 我想要的是这样的:https:domain.com 这就是我试图继续下去的方式,我不知道出了什么问题,因为我遵循了很多例子: 让linkModif=link.replace((/.com.*$/,“.com”)| |(/.ca.*$/,“.ca”); 让源=($(this).find('dc\\:source').text())| | lin

我想保留url的开头,删除其余部分以显示源代码。我所做的是给我这样一个源代码:
https:domainundefined/test1/test2.html
我想要的是这样的:
https:domain.com

这就是我试图继续下去的方式,我不知道出了什么问题,因为我遵循了很多例子:

让linkModif=link.replace((/.com.*$/,“.com”)| |(/.ca.*$/,“.ca”);
让源=($(this).find('dc\\:source').text())| | linkModif

我想我的正则表达式是错的。为什么?

编辑:


我想要一个这样的链接:
唯一的keep

问题是,为replace()提供的表达式比较两个语句并将第一个计算值返回到truthy值:

(...).replace((/.com.*$/, ".com") || (/.ca.*$/, ".ca")); 
// this is evaluated to .replace(".com") but has no second argument to the replace function, so it returns undefined
因此,这里有一个快速解决方案:

let linkModif = link.match(/.com.*$/) ? link.replace(/.com.*$/, ".com") : link.replace(/.ca.*$/, ".ca");
// added a check for the type of domain

如果不显示更多代码,就无法判断jQuery代码的其余部分(第2行)是否正常工作。

您可以这样做。你的问题还不清楚,但希望这对你有用

var link = "https:domain/test1/test2.html"
var modifydomain = link.split('/')[0]

link = link.split('.')
var modifyExnt = link[link.length-1]
var originalLink = modifydomain + '.' + modifyExnt
console.log('originalLink',originalLink)
修改


constURL=新url(myUrl)${url.protocol}${url.hostname}```类似这样的东西很难在上做正则表达式,请提供完整的url和预期输出。我想获取这样的链接:并且只保留我想获取这样的链接:并且只保留@Steph我已经做了更改,我忘记添加协议,请查看
//Without protocol
var url = "http://app.domain.com/Delete/This/Part ";
var domain = url.replace('http://','').replace('https://','').split(/[/?#]/)[0];
console.log(domain) // app.domain.com

//With protocol
var url = new URL("http://app.domain.com/Delete/This/Part");
var protocol = url.protocol;
var domain = url.hostname;
url = protocol + "//" + domain
console.log("Url...........",url) // http://app.domain.com
var link = 'https://example.com/blah';
var tmp = link.match(/https?:\/\/[^\/\?#]*/);
if(tmp) console.log('found '+tmp[0]);