Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to separate words by commas?

I would like to split words with comma, so I can later highlight it with mouse hover.
But I can’t get it to work, I don’t want to split words with - also.

HTML

<p class="texthover"> Name, Name-01, Name-02, Name, Name</p>

CSS

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.texthover span {
    color: #F2668F;
    transition: color .3s;
}

.texthover span:hover {
    color: #023C4F;
    transition: color .3s;
}

First code I have, words are all split:

$(function() {
    $('.texthover').each(function() {
        var $this = $(this);
        $this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
    });
});

I tried it this way too, while I can get the words, I lose the commas in text:

var text = document.querySelector('.texthover').innerHTML;
var old_html = text.split(",");
var new_html = "";
for (var i = 0; i < old_html.length; i++) {
    new_html = new_html + " <span class='text-"+i+"'>" + old_html[i]  + " </span>";
    document.querySelector('.texthover').innerHTML = new_html;
}

>Solution :

Consider the following.

$(function() {
  $(".texthover").each(function(i, el) {
    $(el).html("<span>" + $(el).text().split(", ").join("</span>, <span>"));
  });
});
.texthover span {
    color: #F2668F;
    transition: color .3s;
}

.texthover span:hover {
    color: #023C4F;
    transition: color .3s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="texthover">Name, Name-01, Name-02, Name, Name</p>

This Splits the text, based on Coma, and then joins it all back with the proper Span wrapping and separating coma.

Result:

<span>Name</span>, <span>Name-01</span>, <span>Name-02</span>, <span>Name</span>, <span>Name</span>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading