4 Leave Cover
4 Leave Cover

Reputation: 1276

ASP.NET Using slash in alert()

I would like to prompt the path of the excel file to the user. But I cannot include slashes in the alert function. Here goes my code that works:

Dim sb As New System.Text.StringBuilder() 
sb.Append("<script type ='text/javascript'>window.onload=function(){alert('C:')};</script>")

However, because I need to alert user regarding the path, I need to put e.g. C:\Program Files\New Folder. But when I insert the slash '\' the alert() will not work. Please guide me. Thanks in advance!

Upvotes: 0

Views: 1326

Answers (1)

Ant P
Ant P

Reputation: 25231

You need to escape the slash, like this:

'C:\\\\'

This is because slashes in strings are - in most languages - used to escape special characters, such as, for example, in a newline:

\n

So, if you need the slash to be written out verbatim, you need to escape the slash itself. You need to do this twice - once for C# to escape it and write out 'C:\\' which will then be escaped by Javascript, producing C:\ in your alert.

Alternatively, you can escape it once and use the "verbatim" modifier, which will treat the escape character as a literal backslash instead:

sb.Append(@"<script type ='text/javascript'>window.onload=function(){alert('C:\\')};</script>")

Upvotes: 4

Related Questions