3

I have a bit of code that transforms user input to ensure the only allowed characters are abcdefghijklmnopqrstuvwxyz-0123456789

https://jsfiddle.net/py4pnr0L/

value = 'GHJHlk;sxa787BVK'
value = value.toLowerCase()
value = value.replace(/[^a-z0-9\-]/gi, '-')
console.log(value)

Returns: ghjhlk-sxa787bvk

How would I go about not transforming, but just testing to find if a given string contains characters outside the permitted range?

All I want to know is true/false for a given input string.

I am using ES2015 so if the cleanest solution is available using ES2015 then that is fine.

Duke Dougal
  • 24,359
  • 31
  • 91
  • 123
  • 2
    You mean `/[^a-zA-Z0-9]/.test(value)` ? – anubhava Apr 05 '16 at 21:39
  • Is the set of allowed characters the same? You can just use your own negated character class with `.test()` if yes. `/[^a-z0-9-]/i.test(value)` – Wiktor Stribiżew Apr 05 '16 at 21:39
  • @WiktorStribiżew why does your answer and anubhava's vary in regards to i.test(value) versus .test(value). What does the "i" do? – Duke Dougal Apr 05 '16 at 21:43
  • Erm, it is your regex :) `/i` is a case sensitivity modifier, `/[a-z]/i` = `/[a-zA-Z]/`. Also, my regex includes a hyphen, anubhava's does not. Is that the code you are looking for? – Wiktor Stribiżew Apr 05 '16 at 21:45

2 Answers2

1

you can use match method , try something like:

value = 'GHJHlksxa787BVK';
 
console.log(!value.match(/[^a-zA-Z0-9\-]/))
maioman
  • 18,154
  • 4
  • 36
  • 42
0

You can use RegExp#test() method:

Executes a search for a match between a regular expression and a specified string. Returns true or false.

No /g modifier should be used with this method so that the lastIndex property could not mess the results. See Why RegExp with global flag in Javascript give wrong results? for details.

Your regex /[^a-z0-9-]/i (matches any character that is not in the a-z and A-Z and 0-9 ranges and not -) can be used here. Just take out the /g.

var value = "GHJHlksxa787BVK";
document.body.innerHTML = /[^a-z0-9-]/i.test(value);

The /i is a case insensitive modifier, /[a-z]/i = /[A-Za-z]/.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • A subtlety to the question / my code is that the whitelist does *not* permit upper case characters. Which I guess means taking out the trailing "i" from your regex? – Duke Dougal Apr 05 '16 at 21:54
  • Now, `/[^a-z0-9-]/i` checks if a string contains chars other than `A-Z`, `a-z`, `0-9` and `-`. If you want to trigger `true` when `A-Z` is present, remove the `/i` modifier. – Wiktor Stribiżew Apr 05 '16 at 21:57