Itsik Mauyhas
Itsik Mauyhas

Reputation: 3984

CSS - replace part of content text

Is there a way using pure CSS to replace part of content text, for example if the text is ABCDE -

<span class="replacer">ABCDE</span>

But instead of ABCDE the first 3 chars will be * so it will displayed as ***DE.

Upvotes: 1

Views: 11707

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

No, in pure CSS it's not possible to change the content, but you could cheat by overlapping something, e.g.

.replacer { 
  font-family: monospace; 
  position: relative; }

.replacer::before {
   background: #fff;
   position: absolute;
   content: "***";
}

Codepen demo

or, another tricky way could be creating and loading a special font that maps the symbols A, B and C into the asterisk sign (through the unicode-range property, https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range)


in javascript you would only need to replace the textContent property of the element

var el = document.getElementsByClassName('replacer')[0]
el.textContent = el.textContent.replace(/^.{3}/, '***');

Upvotes: 5

user9674579
user9674579

Reputation:

A solution which works as you want, try to take a look at it

.replacer {
  display: inline-block;
  position: relative;
  font-family:monospace;
  font-size:18px;
}

.replacer:before {
  content: attr(stars);
  background-color: #fff;
  position: absolute;
  left: 0;
}
<span stars="***" class="replacer">ABCDE</span>

To increase the number of stars in beginning, just change the stars attribute in html, similarly same can be done for .replacer::after, see example below

.replacer {
  display: inline-block;
  position: relative;
  font-family:monospace;
  font-size:18px;
}

.replacer:after {
  content: attr(stars);
  background-color: #fff;
  position: absolute;
  right : 0;
}
<span stars="***" class="replacer">ABCDE</span>

Upvotes: 5

Related Questions