1

I've got a string of text that becomes part of the filename that gets saved out. I need to remove any illegal characters (ie non alpha numeric, only latin based characters)

This is what I have so far:

Figured it out, regex-fu levels back to normal!

function isValidFilename(fname)
{ 
  var rexp = new RegExp(/[^a-zA-Z0-9]/gim)
  return fname.replace(rexp, "")
}

var v = "my$filename"
alert(v + "\nis valid???\n\n" + isValidFilename(v))

v = "myfilename"
alert(v + "\nis valid???\n\n" + isValidFilename(v))
Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125

2 Answers2

2

found this in another question:

/^[0-9a-zA-Z\^\&\'\@\{\}\[\]\,\$\=\!\-\#\(\)\.\%\+\~\_ ]+$/

taken from: Javascript regex for validating filenames

Maybe you can use this one to get were you want?

Community
  • 1
  • 1
amaters
  • 2,266
  • 2
  • 24
  • 44
  • I had a look at that link earlier but it hasn't helped my regex-fu :( – Ghoul Fool Jan 30 '13 at 11:01
  • 1
    Yeah? And Отчёт.doc or Kaya - 火車.mp3 is suddenly invalid? No, really? – Oleg V. Volkov Jan 30 '13 at 11:52
  • I've figured it out and adjusted the code. It's not bullet proof (it fails on Отчёт.doc as all letters get replaced; but it was only every designed for English text and that'll do for now. – Ghoul Fool Jan 30 '13 at 12:05
2

You should validate against valid characters instead of removing invalid characters

^ inside a [] group will negate that group.

you can use replace with /[^A-Za-z0-9.-]/ to eliminate all characters that do not belong in this group