0

As the title says, I am looking for help checking if a string contains special characters or spaces (but allowing hyphens, except at the end of the string) in javascript.

For example, if a string is 'laskdfja saldfja sldkfj alsd#$@ @#$KL@ @KL$', return true, and if a string is 'dskfj-dflsk' return false, or 'sdkfj-' return true.

Can anyone help? Thanks in advance?

Mike Johnson Jr
  • 776
  • 1
  • 13
  • 32

2 Answers2

2

This regex: /(?=[^\w-]+|-$)/ will do what you want. It uses a positive lookahead to look for either a non (word character or hyphen) in the string, or that the string ends with a -.

let strings = ['laskdfja saldfja sldkfj alsd#$@ @#$KL@ @KL$',
'dskfj-dflsk',
'sdkfj-'];
console.log(strings.map(s => /(?=[^\w-]+|-$)/.test(s)));
Nick
  • 138,499
  • 22
  • 57
  • 95
0
"SomeString".charCodeAt(0);     //returns 83

Will return a number representing the UTF-16 code unit value of the character at the given index (in this case 0)

You could then loop through your string and check that none of the numbers fall out of the range 48 to 122 (inclusive) or is 45 (the number for hyphen) and then check if the last character is a hyphen

Tristan Warren
  • 435
  • 1
  • 7
  • 17