I have to create:
<input type="text">
<textarea>
<div>
<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)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With