Bhaskar
Bhaskar

Reputation: 1690

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.

Upvotes: 4

Views: 84

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115222

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

Upvotes: 7

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Simple solution using regex pattern and RegExp.test method:

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

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

Upvotes: 2

Max Koretskyi
Max Koretskyi

Reputation: 105489

Since your asked about jquery:

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

Upvotes: 1

Related Questions