1

I am trying to "highlight" specific words in a string after the string has been created.

I'm doing this currently:

var keywords = [
    "Monday",
    "monday",
    "Tuesday",
    "tuesday",
    "Wednesday",
    "wednesday",
    "Thursday",
    "thursday",
    "Friday",
    "friday",
    "Saturday",
    "saturday",
    "Sunday",
    "sunday"
    ];    

function highlightImportant(that) {
    that.find('.email-container').each(function(){
        var full_text = $(this).text();
        $.each(keywords, function(i){
            full_text = full_text.replace(keywords[i], "<b>"+keywords[i]+"</b>");
            $(this).text(full_text);
        });
    });
}

this function is called at the end of this:

function getEmails(email, name) {
    console.log("working...");
    $('.contact--details__show__emails').empty();
    $.post('php/contacts-get-email.php', {email:email}, function(data) {
        var email_body = data.split("<:>");
        $.each(email_body.reverse(), function(i){
            if(email_body[i]) {
                var direction = email_body[i].split(':dir:')[0];
                var email_text = email_body[i].split(':dir:')[1].split(':date:')[0];
                var email_date = email_body[i].split(':dir:')[1].split(':date:')[1];
                var d = new Date(0);
                d.setUTCSeconds(email_date);
                if(direction === "TO"){
                    var initial = "Us"; 
                } else {
                    var initial = name; 
                }
                var email_block = $('<div class="emailBlock dir-'+direction+'" style="opacity:0;">\
                                    <div class="avatar">'+ initial +'</div>\
                                    <div class="email-container">'+email_text+'</div>\
                                    <div class="date">'+d+'</div>\
                                </div>');
                $('.contact--details__show__emails').append(email_block);
                email_block.delay(100*i).animate({"opacity":"1"}, 500);
                highlightImportant($('.contact--details__show__emails'));
            }
        }); 
    }); 
}

This seems like it should work, and when I console.log the event, I see it running through each keyword for every container, but it seems it's not finding the keywords even when they exist.

What I'd like to see happen is when I have a string like this:

var string = "Let's meet Monday or Tuesday";

I'd like to have them turn bold, like so:

"Let's meet Monday or Tuesday"

Any thoughts?

7
  • Strings are immutable hence .replace(...) returns a new string -> full_text = full_text.replace(...) Commented Nov 16, 2015 at 23:57
  • Oh, so I need to make it a variable, then replace the text... Commented Nov 16, 2015 at 23:58
  • can you should the html and js that eventually calls highlightImportant? Commented Nov 17, 2015 at 0:04
  • ideally put it all in a jsFiddle so we can try it ourselves Commented Nov 17, 2015 at 0:04
  • @gabriel, I will try. Unfortunately, there's an AJAX call that I won't be able to simulate, but I'll work something out Commented Nov 17, 2015 at 0:05

3 Answers 3

2

Two problems. First of all your $(this) in your $.each loop is not the DOM-Element! Second problem: you use $(this).text(full_text) but you want to set ....html(full_text). You are using html tags to highlight the words (<b>) which would be removed if you use text

var keywords = [
    "Monday",
    "monday",
    "Tuesday",
    "tuesday",
    "Wednesday",
    "wednesday",
    "Thursday",
    "thursday",
    "Friday",
    "friday",
    "Saturday",
    "saturday",
    "Sunday",
    "sunday"
    ];    
function highlightImportant(that) {
    that.find('.email-container').each(function(){
        var full_text = $(this).html(),
            element = $(this);
        $.each(keywords, function(i){
            full_text = full_text.replace(keywords[i], "<b>"+keywords[i]+"</b>");
        });
        element.html(full_text);
    });
}

highlightImportant($("#container"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    <div class="email-container">Let's meet Monday or Tuesday</div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Move the element.html(full_text) out of the $.each(). There's no need to update the content for each keyword separately.
Wow, I must be tired. What simple mistakes!! Thank you, I will try this out shortly when I get a chance and report back
1

You have two errors in this line:

$(this).text(full_text);

1) this points to string rather to DOM element and 2) you should use html() method if you want markup to go into element.

And String.replace() in that form you use will replace only first entry, so you should do this:

that.find('.email-container').each(function(){
        var full_text = $(this).text();
        $.each(keywords, function(i) {
            full_text = full_text.replace(new RegExp(keywords[i],"gi"), "<b>"+keywords[i]+"</b>");
        });
        $(this).html(full_text);
    });

1 Comment

Accepted answer for the information on .replace() and the fix using regex. Thank you!
1

A simpler solution:

var string = "Let's meet Monday or Tuesday";

function highlightKeyword(string) {
  return string.replace(/(Monday|monday|Tuesday|tuesday|Wednesday|wednesday|Thursday|thursday|Friday|friday|Saturday|saturday|Sunday|sunday)/g, "<strong>$&</strong>");
}

$('p').html(highlightKeyword(string));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p></p>

1 Comment

Yes, simple, though I will be using more words than just the days of the week. I'm sorry I didn't mention that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.