20

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.

ngplayground
  • 20,365
  • 36
  • 94
  • 173
  • http://stackoverflow.com/questions/4444477/how-to-tell-if-a-string-contains-a-certain-character-in-javascript – topcat3 Mar 06 '13 at 11:23
  • What specifically are you trying to do? The answers below does exactly what you ask for, but there might be a better way to go depending on what you're trying to achieve. – qwerty Mar 06 '13 at 11:26
  • Use indexOf it will be faster also – Peeyush Mar 06 '13 at 11:29

4 Answers4

37

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.

yckart
  • 32,460
  • 9
  • 122
  • 129
7

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 > <');        
    }
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
7

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}
topcat3
  • 2,561
  • 6
  • 33
  • 57
2

use Contains of jquery Contains like this

if ($('.type:contains("> <")').length > 0)
{
 //do stuffs to change 
}
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83