how to check if a string contains substring and color it in javascript?
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/
以下是查找和更改所有搜索词的颜色的代码
$(document).ready(function () {
$("#here").on("keydown keyup", function () {
var mytext = $(this).val();
var find = $("#find").val();
mytext=mytext.replace(new RegExp(find,"g"), "<span class='me'>"+find+"</span>");
$("#output").html(mytext);
});
})
.me{color: #00f;
background-color: #EFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="find" type="text" /><br/>
<textarea id="here"></textarea><br/>
<div id="output"></div>
Use JavaScript substring
to split the string inside textarea and form a paragraph
with the highlighted text.
HTML code:
<input id="inp1" type="text"/><br>
<textarea id="txt" col="10" row="5"></textarea><br>
<div id="fillarea">
click on check
</div>
<button id="check">check</button>
CSS for highlighting:
.highlight{
background-color:yellow;
}
jQuery code:
$('#check').on('click',function(){
var a = $("#inp1").val();
var b = $("#txt").val();
var x = b.indexOf(a);
var first = b.substring(0,x);
var middle = b.substring(x,x+a.length);
var last = b.substring(x+a.length,b.length);
var to_print = '<p>' + first + '<span class="highlight">' + middle + '</span> ' + last + '</p>';
$('#fillarea').empty();
$('#fillarea').append(to_print);
});
Demo fiddle here
链接地址: http://www.djcxy.com/p/25742.html上一篇: 为什么Azure AD无法登录非