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.
You could use String.prototype.indexOf
to accomplish that. Try something like this:
$('.type').keyup(function() {
var v = $(this).val();
if (v.indexOf('> <') !== -1) {
console.log('contains > <');
}
console.log(v);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="type"></textarea>
Update
Modern browsers also have a String.prototype.includes
method.
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}
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