How to check part of an array of string matches

I have an array like this

var invalidChars = ["^", "_", "[", "]"];

var inputText = "abc^"   - true
var inputText = "abc_"   - true
var inputText = "abc"    - false

Can someone please let me know how I can check if my input line contains any elements in the array using jQuery / Javascript?

I tried $ .InArray and indexof. it does not work like those that check the whole string.

+4
source share
3 answers

You can use and some() indexOf()

some() , , , , . , some() true. some() false. callback , ; , . ( )

var invalidChars = ["^", "_", "[", "]"];

var inputText = "abc^";
var inputText1 = "abc_";
var inputText2 = "abc";

console.log(
  invalidChars.some(function(v) {
    return inputText.indexOf(v) != -1;
  }),
  invalidChars.some(function(v) {
    return inputText1.indexOf(v) != -1;
  }),
  invalidChars.some(function(v) {
    return inputText2.indexOf(v) != -1;
  })
)
Hide result

polyfill some().

regex . .

var invalidChars = ["^", "_", "[", "]"];

var inputText = "abc^";
var inputText1 = "abc_";
var inputText2 = "abc";

var regex = new RegExp(invalidChars.map(function(v) {
  return v.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
}).join('|'));

console.log(
  regex.test(inputText),
  regex.test(inputText1),
  regex.test(inputText2)
)
Hide result

regex:

+7

RegExp.test:

var re = /[\^\[\]_]/;

console.log(re.test("abc^"));  // true
console.log(re.test("abc_"));  // true
console.log(re.test("abc"));   // false
+2

So how is your jquery question:

var contains, inputText;
var invalidChars = ["^", "_", "[", "]"];

inputText = "abc^"   // true
contains = $(invalidChars).filter(inputText.split('')).length > 0; // true

inputText = "abc_"   // true
contains = $(invalidChars).filter(inputText.split('')).length > 0; // true

inputText = "abc"    // false
contains = $(invalidChars).filter(inputText.split('')).length > 0; // false
+1
source

All Articles