brosen bro
brosen bro

Reputation: 11

How to avoid If and else in spread operator Javascript

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

Answers (3)

Jonas Wilms
Jonas Wilms

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

user1429980
user1429980

Reputation: 7148

We can approach this refactoring through 3 steps:

  1. Move the document.querySelectorAll('a') to the top
  2. Filter the resulting <a> tags that match our criteria through our selector through the ~= selector
  3. Return the results in our function

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

Klaycon
Klaycon

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

Related Questions