我有一個這樣的網址陣列:
[
'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'
]
我需要在其中搜索以將用戶輸入與subdomainurl 的一部分相匹配,我正在嘗試使用這行代碼來實作它:
const searched = urlList.find( el => el.includes( match[1].toLocaleLowerCase() ) )
console.log(searched.length)
如果輸入是 find,我需要替換 url 的第二部分,在我的情況下/foo-bar,用/foo-bazor/foo-baz-bar為用戶獲取類似于https://subdomain2.example.com/foo-bar-baz/.
目前我不確定如何繼續,JS中有什么功能可以幫助我嗎?
uj5u.com熱心網友回復:
您可以通過一行代碼簡單地實作這一點。
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);
uj5u.com熱心網友回復:
查找域并用正則運算式替換部分 URL
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));
}
uj5u.com熱心網友回復:
我找到了一個簡單的解決方案并解決了問題這是我的片段,供將來需要相同東西的每個人使用
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}`
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453913.html
標籤:javascript 节点.js 数组 正则表达式
