Author Topic: [PJSR] Method to clean file name  (Read 4770 times)

Offline bitli

  • PTeam Member
  • PixInsight Guru
  • ****
  • Posts: 513
[PJSR] Method to clean file name
« on: 2015 February 03 11:24:33 »
Hello,
I use data of FITS fields (as EXTNAME) to create a file name.  Is there a method to 'clean' a file name, that is to remove/transform characters that may be troublesome (.., / \, quotes, ....).  I have seen nothing in Files.
Same question to create a PI identifier from an arbitrary text (as replacing _ par -, or something).  Naturally the transformation is not invertible and do not maintain unicity, but this could be convenient.
-- bitli

Offline Juan Conejero

  • PTeam Member
  • PixInsight Jedi Grand Master
  • ********
  • Posts: 7111
    • http://pixinsight.com/
Re: [PJSR] Method to clean file name
« Reply #1 on: 2015 February 03 11:39:25 »
Quote
create a PI identifier from an arbitrary text

How about this:

Code: [Select]
function toValidViewId( s )
{
   return s.replace( /[^_a-zA-Z0-9]/g, '_' ).replace( /[^_a-zA-Z]/, '_' );
}

Edit: fix a problem with strings starting with a decimal digit.
Juan Conejero
PixInsight Development Team
http://pixinsight.com/

Offline bitli

  • PTeam Member
  • PixInsight Guru
  • ****
  • Posts: 513
Re: [PJSR] Method to clean file name
« Reply #2 on: 2015 February 03 11:43:50 »
Fine by me, didn't know if there was already a 'standard' way (although it should probably not start by a digit also).
tks.

Offline mschuster

  • PTeam Member
  • PixInsight Jedi
  • *****
  • Posts: 1087
Re: [PJSR] Method to clean file name
« Reply #3 on: 2015 February 03 12:29:44 »
May also want to guarantee that name is not empty ""? May want to trim off leading and trailing spaces?

Mike

Offline mschuster

  • PTeam Member
  • PixInsight Jedi
  • *****
  • Posts: 1087
Re: [PJSR] Method to clean file name
« Reply #4 on: 2015 February 03 12:40:38 »
Hi Juan,

Your decimal digit fix introduced a bug. Should apply to first character only (add another ^ to second replace):

Code: [Select]
return s == "" ? "_" : s.replace( /[^_a-zA-Z0-9]/g, '_' ).replace( /^[^_a-zA-Z]/, '_' );

Mike