javascript - Check if variable contains any characters in array -


i have following javascript, disallow file being named specific name, , disallow characters appearing anywhere in name:

var file = 'somefile'; var contain = ['"', '*', ':', '<', '>', '?', '\\', '/', '|', '+', '[', ']']; var fullname = ['aux', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7',   'com8', 'com9', 'con', 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7',   'lpt8', 'lpt9', 'nul', 'prn'];  if(fullname.indexof(file.touppercase()) >= 0) {     alert('your file must not named of these words:\n\n' +       fullname.join(' '));     return; }  if(/* file contains chars in contain[] */) {     alert('your file name must not contain of these characters:\n\n' +       contain.join(' '));     return; } 

i'm wondering how can check if file contains of items in contain array.

i use for loop, so:

for(var = 0; < contain.length; i++)     if(file.indexof(contain[i]) >= 0)         ... 

but seems "wrong" use loop this.

is there built-in function using vanilla javascript?

if you're using .indexof() loop way go.

however, use regex:

var contain = /["*:<>?\\/|+\[\]]/; var fullname = /^(aux|com1|...)$/i;   // nb: "i" flag case insensitive  if (contain.test(file)) {     ... }  if (fullname.test(file)) {     ... } 

this ought pretty efficient regex processed in native code within js interpreter.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -