Reputation: 11
I am quite new to JS. I am trying to simplify my code but its throwing me an syntax error. Is there any way I can avoid multiple codes like not using If and else statement. Below is the code I posted for reference.
the only difference is item.href.replace statement will have "?".
(() => {
const test = 'x=abc';
if (location.search == "") {
[...document.querySelectorAll('a')]
.filter(link => link.href.includes(test))
.forEach(item => (item.href = item.href.replace(`${test}`, location.search)));
} else {
[...document.querySelectorAll('a')]
.filter(link => link.href.includes(test))
.forEach(item => (item.href = item.href.replace(`?${test}`, location.search)));
}
})();
Upvotes: 1
Views: 115
Reputation: 138257
Well, the actual clean solution would be:
[...document.querySelectorAll('a')]
.filter(link => link.href.includes(test))
.forEach(link => link.search = link.search.replace(test, location.search));
Upvotes: 1
Reputation: 7148
We can approach this refactoring through 3 steps:
document.querySelectorAll('a')
to the top<a>
tags that match our criteria through our selector through the ~=
selectorfunction
The resulting code might look something like this:
const replaceQueryParams = function(test) {
const matchingLinks = [...document.querySelectorAll(`a[href~="${test}"]`)];
return matchingLinks.map((link) => link.href = link.href.replace(`?${test}`, window.location.search));
};
We can then use the replaceQueryParams
function like so:
const replacedLinkStrings = replaceQueryParams("my-test-string");
if (replacedLinkStrings.length > 0) {
console.log("Do something here");
}
Upvotes: 0
Reputation: 11080
You can simply assign the string you want before the operation.
const test = 'x=abc';
let search = (location.search == "") ? test : `?${test}`;
[...document.querySelectorAll('a')]
.filter(link => link.href.includes(test))
.forEach(item => (item.href = item.href.replace(search, location.search)));
Upvotes: 3