Highlight text by keywords which are separated by comma

I would like to split up text by comma - i.e. keywords are as the following:

keyword1, keyword2, keyword3, keyword4

How can I have a the black style element for each and every keyword that is separated by a comma. Is there an easy way to do this? The text is always dynamic, so I never know exactly what those keywords will be and how many. So each keyword should have a box elements around it.

<span class="keyword-option-black">keyword1, keyword2, keyword3, keyword4</span>

.keyword-option-black {
    color:white;
    background-size:contain;
    margin:10px;
    padding:5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    background:black;
}

Answers:

Answer

CSS is unable to select text.

In order to highlight the keywords on a page, you need to use programming languages such as JavaScript (for client-side) or PHP (or whatever else for server-side) to wrap the keywords by a wrapper element which has a special CSS style to distinguish the keys.

Here, I implemented the above approach by using jQuery (just to demonstrate):

Working Fiddle

JS part:

// Insert the keywords here,
// you can also get the keys automatically from the DOM if needed
var keywords = ['Google', 'Facebook', 'Social'];

$.each(keywords, function(index, key) {
    var $content = $('#content'),
        text = $content.html();

    $content.html(
        text.replace(
            new RegExp("("+ key +")", 'ig'), "<span class='highlight'>$1</span>"
        )
    );
});

And here is the highlight class:

.highlight {
    color: white;
    background-size: contain;
    margin:10px;
    padding:5px;
    border-radius: 5px;
    background: black;
}
Answer

HTML and CSS are static. Since you don't know how many keywords are gonna be there, you need something dynamic. Depending on implementation, you can use JavaScript or any Back-end language you are using.
Basically, you want to add a span tag around each keyword and style that span (span in one with class keyword-option-black). So, when you enter keywords to HTML use <span>keywordX</span> in loop that adds elements or, alternatively, add those tags when document loads using JavaScript.
Hope this helps.

Answer

Using Django, I did it the following way.

  1. Create a simple CSS class to perform the highlighting.
  2. Create a custom tag that splits up data in template view into <span class="keyword">A</span><span class="keyword">B</span>. It takes the original view output and parses this into a format that already has the spans included.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.