Demsaas Demsaas - 4 months ago 7
HTML Question

Find word in a text and make founded words in a text bold and color:red

Cant get how to change style of founded word,i know two ways how to find,like with indexof and regex but how to change style with founded index or etc?So if shortly i want to do smthing like that:
words to find:
osq,kkw
Text:
aaa bbb osq osqqjweqj kkw

$(".findwords").click(function()
{
var text = $("#text").val();
var words = $("#words").val();
var arrword = words.split(',');
$.ajax({
beforeSend:function()
{
$("#lback-words").show();
$("#lback-text").show();
$('.loader').show();
},
url: "/Demo2/Fwords/",
data: data = { "text": text, "words": words },
method: 'POST',
dataType: 'json',
success: function (data) {
$('#text').val(' ');
$('#words').val(' ');
setTimeout("$('.loader').hide()", 3000);
setTimeout("$('#lback-words').hide()", 3000);
setTimeout("$('#lback-text').hide()", 3000);
console.log(data);
var sub_ul = $('<ul/>');
$.each(data, function (index, value) {
console.log(value);
var sub_li = $('<li/>');
$(sub_li).html(value.w + "-" + value.q);
$(sub_li).appendTo(sub_ul);
});
var appendContent = $("<section class='searchresult'><h4>Result:</h4><div class='words'>Words:</div><div class='text'>Text:<br>" + text + "</div></section>");
$(appendContent).find(".words").append(sub_ul);
$(".texnwords").append(appendContent);
},
error: function (data) {
console.log(data);
}
})

Answer

Try this:

var html = $('.your_text_element').html();
html  = html.replace('osq', '<b>osq</b>');
$('.your_text_element').html(html);

update:

// get values of text and words
var text = $("#text").val();
var words = $("#words").val();
// check if text contains words
var text_after_check = text.replace( words, '<b>' + words + '</b>');
if( text != text_after_check ){
    // words found
    // add html with hightlighted text to div check_result
    $('#check_result').html(text_after_check);
    // hide textarea (optional)
    $("#text").toggle();        
}

In yout html add the div with id = check_result