Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check part of string matches array

I have an array like this

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

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

Can any one please let me know how can I check if my input string contains any items in array using jQuery/Javascript?

I tried $.InArray and indexof . its not working as those check for whole string.

like image 288
Bhaskar Avatar asked Dec 25 '22 05:12

Bhaskar


1 Answers

You can use some() and indexOf()

some() executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some() immediately returns true. Otherwise, some() returns false. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. ( Taken from here )

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

For old browser check polyfill option for method some().

Also you can use regex to achieve the result. Generate the regex using the array and check for match in string.

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)
)

Refer this answer for string to regex conversion : Converting user input string to regular expression

like image 167
Pranav C Balan Avatar answered Dec 26 '22 20:12

Pranav C Balan