[英]node - How to replace part of an url
我有一组这样的网址:
[
'https://subdomain1.example.com/foo-bar/',
'https://subdomain2.example.com/foo-bar',
'https://subdomain2.example.com/foo-bar',
'https://subdomain2.example.com/foo-bar',
'https://subdomain2.example.com/foo-bar'
]
我需要在其中搜索以将用户输入与 url 的subdomain
部分相匹配,我正在尝试使用这行代码来实现它:
const searched = urlList.find( el => el.includes( match[1].toLocaleLowerCase() ) )
console.log(searched.length)
如果找到输入,我需要用/foo-baz
或/foo-baz-bar
替换 url 的第二部分,在我的例子中是/foo-bar
bar 以获得类似于https://subdomain2.example.com/foo-bar-baz/
。
目前我不确定如何进行,JS 中是否有任何 function 可以帮助我?
您只需使用一行代码即可实现。
const urlList = [ 'https://subdomain1.example.com/foo-bar/', 'https://subdomain2.example.com/foo-bar', 'https://subdomain2.example.com/foo-bar', 'https://subdomain2.example.com/foo-bar', 'https://subdomain2.example.com/foo-bar' ]; const findSubString = 'foo-bar'; const replaceSubString = 'foo-baz'; const res = urlList.map((url) => url.replace(findSubString, replaceSubString)); console.log(res);
我找到了一个简单的解决方案并解决了问题这是我的代码片段,供将来需要相同东西的每个人使用
const searched = urlList.find( el => el.includes( match[1].toLocaleLowerCase() ) )
const url = new URL(searched)
const host = url.host
const responseURL = `https://www.${host}${responsePath}`
function foo() {
let a = ['https://subdomain1.example.com/foo-bar/', 'https://subdomain2.example.com/foo-bar', 'https://subdomain2.example.com/foo-bar', 'https://subdomain2.example.com/foo-bar', 'https://subdomain3.example.com/foo-bar'];
let seed = 'subdomain2.example.com';
let repl = 'whatever';
for (let i = 0; i < a.length; i++) {
let e = a[i];
let r = e.match(/\/\/([^\/]+)/);
if (r[1] == seed) {
a[i] = e.replace(/(?<=\.\w{3}\/)[a-zA-Z0-9_-]+/, repl);
}
}
//document.getElementById("jj").value = JSON.stringify(a);
console.log(JSON.stringify(a));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.