0

I have a string like:

"something | other thing / another thing"

But I need to remove all characters that can't be in a file name (like | or /) because I need to save a file with that string using node.

The real problem here is that I can't predict how this string is coming. I tried using some regex expressions that i found in internet but no success.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135

2 Answers2

1

What characters are (or are not) legal in a file name or a file system path is entirely dependent upon your operating system and the underlying file system.

Assuming that you know the set of disallowed characters, it should be as simple as something like this:

function cleanFileName( s ) {
  return s.replace( /[set-of-disallowed-characters-here]/g, '' );
}

or you could get fancier and do something like this:

function cleanFileName( s ) {
  return s.replace( /[set-of-disallowed-characters-here]/g, '-' )
          .replace( /-+/g, '-' );
}

So if your set of disallowed characters contains the punctuation below, the above would turn this

abc!/~dev\|/foo

into

abc-dev-foo
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
0

As @Muhammad Ovi suggested, you could use some library to create a valid URI, in this case Slugify could get the job done.

Have a nice one.

Cryptocurrency
  • 76
  • 1
  • 2
  • 8