开发者

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 data开发者_开发问答base 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?


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.


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

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


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.


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.


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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜