I have an array of urls like this:
JavaScript
x
8
1
[
2
'https://subdomain1.example.com/foo-bar/',
3
'https://subdomain2.example.com/foo-bar',
4
'https://subdomain2.example.com/foo-bar',
5
'https://subdomain2.example.com/foo-bar',
6
'https://subdomain2.example.com/foo-bar'
7
]
8
I need to search inside it to match the user input with the subdomain
part of the url, I’m trying with thism line of code to achive it:
JavaScript
1
3
1
const searched = urlList.find( el => el.includes( match[1].toLocaleLowerCase() ) )
2
console.log(searched.length)
3
If the input is find, I need to replace the second part of the url, in my case /foo-bar
with /foo-baz
or /foo-baz-bar
to obtain a response for the user that is something like https://subdomain2.example.com/foo-bar-baz/
.
At the moment I’m not sure how to proceed, is there any function in JS that can help me?
Advertisement
Answer
You can simply achieve that with a single line of code.
JavaScript
1
14
14
1
const urlList = [
2
'https://subdomain1.example.com/foo-bar/',
3
'https://subdomain2.example.com/foo-bar',
4
'https://subdomain2.example.com/foo-bar',
5
'https://subdomain2.example.com/foo-bar',
6
'https://subdomain2.example.com/foo-bar'
7
];
8
9
const findSubString = 'foo-bar';
10
const replaceSubString = 'foo-baz';
11
12
const res = urlList.map((url) => url.replace(findSubString, replaceSubString));
13
14
console.log(res);