Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a string contains substring and color it in javascript?

I have to create:

  • 1 <input type="text">
  • 1 <textarea>
  • 1 <div>
  • 1 <button>

I have to fill the div with the textarea's content but if the content contains the input's string, I have to color it with <span>.

For example:

If the input contains "is" and the textarea contains "this is a beautiful day", I should put the following text in the div "this is a beautiful day" and color every time that the "is" string appears.

I should use indexOf() and a loop.

I have this:

var a = $("#inp1").val();
var b = $("#txt").val();

var x = b.indexOf(a);
    if (x > -1)
like image 585
moral17592 Avatar asked Apr 22 '15 12:04

moral17592


1 Answers

If you absolutely have to use indexOf

while(b.indexOf(a) != -1) {
   b = b.replace(a, '[X]');
}
while(b.indexOf('[X]') != -1) {
   b = b.replace('[X]', '<span style="color:yellow;">' + a + '</span>');
}
$("#targetDiv").html(b);

You can also do this with RegExp

var a = $("#inp1").val();
var b = $("#txt").val();
var re = new RegExp(a, 'g');
var divContent = b.replace(re, '<span style="color:yellow;">' + a + '</span>');
$("#targetDiv").html(divContent);

Here is a fiddle with the indexOf

http://jsfiddle.net/eva3ttuL/1/

like image 188
JuniorDev Avatar answered Oct 24 '22 02:10

JuniorDev