简体   繁体   中英

How could i check if a string contains an element of an array

I have a textarea, and I need to check if this textarea.value contains a string from a string array. Every onkeyup in textarea I call this script. I tried this code, but something went wrong. "@" is ok, but "apple" and "orange" is not. Please help me! Thanks!

var str = document.getElementById("messageArea").value;

var arr = ["@", "apple", "orange"];

for (var i = arr.length - 1; i >= 0; --i) {
    if (str.indexOf(arr[i]) != -1) {
      alert('contains');
   } else {
        alert('not contains');
    }
}

Break the loop when the message contains the substring.

 $("#messageArea").on("keyup",function(e){ var str = document.getElementById("messageArea").value; var arr = ["@", "apple", "orange"]; for (var i = arr.length - 1; i >= 0; --i) { if (str.indexOf(arr[i]) != -1) { $('#messageBtn').prop('disabled',false); break; } else { $('#messageBtn').prop('disabled',true); } } }); 
 <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-1.11.3.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <textarea type="text" id="messageArea"></textarea> <button disabled id="messageBtn">submit</button> </body> </html> 

var str = "@ apple orange"; //document.getElementById("messageArea").value;

var arr = ["@", "apple", "orange"];


str = str.trim();

var parts = str.split(" "); // split textarea string by space into another array

for (var part in  parts) { // iterate one every part and check it with your arr variable
  if ( arr.indexOf(parts[part]) != -1 ) {
    alert("found: " + parts[part] );
  } else {
    alert("not contains " + parts[part]);
  }
}

you will get alerts for all 3 elements in the str variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM