Sharon
Sharon

Reputation: 1

Forward slash in a JavaScript variable

I have the code below.

{
    var custname= "@1";
    var file = "c:/temp/"+ custname + ".txt";
    var fso  = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.CreateTextFile(file, true, false);
    fh.Write(text);
    fh.Close();
}

The @1 is coming from a database and it's a customer's name. The above code works until I came across a customer name with a forward slash in it, e.g. "Company A/S".

How do I make this work for customers with the forward slash?

Upvotes: 0

Views: 5237

Answers (5)

kasdega
kasdega

Reputation: 18786

If it's Windows you can't have a file name with "/" in it so personally I'd just replace all "/" with something else.

var file = "c:/temp/"+ custname.replace(/\//g, "-") + ".txt";

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

Replace any slashes in the customer name with another character (e.g. an underscore).

var custname= "@1";
custname = custname.replace(/\//g, '_');
...

Note the use of the g modifier on the regular expression to ensure that every slash character is replaced.

This is also why a regexp is used instead of just '/' - the substring version of String.replace won't handle repeated occurences.

Upvotes: 7

QuentinUK
QuentinUK

Reputation: 3077

Store an id, eg a number, for each customer in the database and get the database to return this. Use the number for the filename. If you then need the name do another query.

Upvotes: 0

slandau
slandau

Reputation: 24052

You're creating the file from the customers name as well, so when they have a '/' in their name, the file directory could look something like:

var custname= "/isuck";
var file = "c:/temp/"+ custname + ".txt";

File would equal:

c:/temp//isuck.txt

Which wouldn't be a valid file. The SMART move would be to not allow any '/' marks in a customer name, which really doesn't make sense away. Or if they HAVE to put it in that way, remove the '/' before storing it, or replace it with another character.

Upvotes: 0

highlycaffeinated
highlycaffeinated

Reputation: 19867

You can replace (or delete) any characters not allowed by the filesystem. For example:

custname = custname.replace(/[/|&$]/g, '');

Upvotes: 1

Related Questions