Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery detect if string contains something

Tags:

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.

like image 980
ngplayground Avatar asked Mar 06 '13 11:03

ngplayground


2 Answers

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.

like image 134
yckart Avatar answered Sep 18 '22 16:09

yckart


You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}
like image 32
topcat3 Avatar answered Sep 17 '22 16:09

topcat3