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.

3
  • stackoverflow.com/questions/4444477/… Commented Mar 6, 2013 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. Commented Mar 6, 2013 at 11:26
  • Use indexOf it will be faster also Commented Mar 6, 2013 at 11:29

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

7

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}

Comments

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 > <');        
    }
});

Comments

2

use Contains of jquery Contains like this

if ($('.type:contains("> <")').length > 0)
{
 //do stuffs to change 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.