Aswin KV Aswin KV - 7 months ago 96
Sass (Sass) Question

How can we style a word in css with special character?

I made an application in angular 2(5.0). The application is all about getting the trending tweets.

I faced one problem while styling. I am getting one paragraph though API

Eg:

@_NAN_DINI @InTheWordsOfK @maidros78 Self immolation is still a form of social protest in India. Remember the guy w…


My need is, i want to give additional style to the words which having characters like
#
and
@


Eg:


  • @_NAN_DINI

  • @InTheWordsOfK

  • @maidros78

  • #ereaad



So is it possible to add some basic style to these kind of word without heavy JavaScript ??
Can we solve it with CSS ? How ?

Note: I am using SCSS.

Answer Source

This is not something that can be done with only CSS. You will need JavaScript and the example below in raw JS without the need for any framework, but it can be use in any framework.

Try this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Twitter CSS 1</title>
    <style>
     #input {
       font: 14px/1.2em Tahoma;
       height: 12em;
       width: 500px;
     }

     .class-at {
       color: blue;
     }

     .class-hash {
       color: green;
     }
    </style>
  </head>
  <body>
    <h3>Enter Text Here</h3>
    <textarea id="input">@_NAN_DINI @InTheWordsOfK @maidros78 Self immolation is still a form of social protest in India. Remember the guy w…</textarea>
    <hr/>
    <div id="output"></div>
    <script>
    var inEl = document.getElementById('input');
    var outEl = document.getElementById('output');

    function encodeStr(str) {
      return str.replace(/(\@\S+)/g, (key) => `<span class="class-at">${key}</span>`).replace(/(\#\S+)/g, (key) => `<span class="class-hash">${key}</span>`);
    }

    function inputHandler() {
      outEl.innerHTML = encodeStr(inEl.value);
    }

    inEl.addEventListener('input', inputHandler);
    inputHandler();
    </script>
  </body>
</html>

See: https://jsfiddle.net/intervalia/bu3rxq8q/

The function encodeStr contains two calls to replace. And those add either a <span class="class-at"> or a <span class="class-hash"> around the words you are looking for.

All that is needed

The function encodeStr is all the JS that is really needed to do the conversion. It is up to you to get the string into the function and use the result. You will also need the CSS that colors your fields the color you want. .class-at and .class-hash. Of course you can change those to whatever you want them to be called.

function encodeStr(str) {
  return str.replace(/(\@\S+)/g, (key) => `<span class="class-at">${key}</span>`).replace(/(\#\S+)/g, (key) => `<span class="class-hash">${key}</span>`);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download