ngplayground ngplayground - 4 months ago 39
jQuery Question

jQuery detect if string contains something

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.

Answer

You could use String.prototype.indexOf to accomplish that. Try something like this:

$('.type').keyup(function() {
  var val = this.value;
  if ( val.indexOf('> <') !== -1 ) {
    console.log('contains ', val);        
  }
});

http://fiddle.jshell.net/7AuK2/