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.
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;
})
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With