I'm trying to write jQuery code to detect if a live string contains a specific set of characters then the string alerts me.
HTML
<textarea class="type"></textarea>
My Jquery
$('.type').keyup(function() {
var v = $('.type').val();
if ($('.type').is(":contains('> <')")){
console.log('contains > <');
}
console.log($('.type').val());
});
if for example I typed the following
> <a href="http://google.com">Google</a> <a href="http://yahoo.com">Yahoo</a>
My code should console log alert me that there > < present in the string.
This question is related to
jquery
You could use String.prototype.indexOf
to accomplish that. Try something like this:
$('.type').keyup(function() {_x000D_
var v = $(this).val();_x000D_
if (v.indexOf('> <') !== -1) {_x000D_
console.log('contains > <');_x000D_
}_x000D_
console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
Update
Modern browsers also have a String.prototype.includes
method.
You get the value of the textarea, use it :
$('.type').keyup(function() {
var v = $('.type').val(); // you'd better use this.value here
if (v.indexOf('> <')!=-1) {
console.log('contains > <');
}
});
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}
use Contains of jquery Contains like this
if ($('.type:contains("> <")').length > 0)
{
//do stuffs to change
}
Source: Stackoverflow.com