Replace the matched group with spaces

Viewed 60

Here is the contents of the <style> tag of my HTML document:

<style>
        a:link { color: blue; }
  a:link:hover { color: red;  }
</style>

As you see rules are aligned by the opening brace.

Now I need to to remove the :link part from the second rule and keep the alignment in tact.

Here is what I have:

function getStyleAndChangeIt() {
  let style = document.querySelector('style').innerText;
  style = style.replace(/(a)(?::link)(:hover|:focus|:active)/g, '$1$2');
  return style;
}

It doesn't solve the task, of course. It simply removes the :link part without keeping the alignment in tact.

So how to change it so that it will work exactly as I want it? Cheers.

It is actually necessary to replace the :link part with spaces and place these spaces before a, but I don't know how.

edit:

In other words, the desired output is:

   a:link { color: blue; }
  a:hover { color: red;  }
2 Answers

You can add 5 spaces (the length of :link) before $1 in the substitution argument, and use

const text = `<style>
        a:link { color: blue; }
  a:link:hover { color: red;  }
</style>`;
console.log(text.replace(/(a):link(:(?:hover|focus|active))/g, "     $1$2"));

Note you do not need a non-capturing group in (?::link), it is the same as :link. You only need the group if you intend to use alternation or quantify the group pattern sequence.

All the things I changed are comments in the function.

function getStyleAndChangeIt() {
  // I wasn't able to make the snippet without changing the style tag, but you should change it back in your code
  // I also had to use innerHTML not innerText, because of extra white spaces. That's why the spacing was removed.

  let style = document.querySelector('pre').innerHTML;
  style = style.replace(/(a)(?::link)(:hover|:active|:focus)/gm, '$1$2');

  // since you know a is meant to be the first letter no need to put it in a group
  // I also removed the colon in front of the pseudo-classes since they all have it

  return style;
}

console.log(getStyleAndChangeIt())
<pre>        
        a:link { color: blue; }
  a:link:hover { color: red;  }
</pre>

Related