-2

I have a file that has an extention either:

.doc or .docx

I wanted to link it this way:

document.getElementById("file").innerHTML = "View file sent <a href='../folder/filename" +
(what syntax do I need to add here if I wanted to print which extention file is exist on that folder)

In PHP we can do this

var1 = ".doc";
var2 = ".docx";

var1 ? var1 : var2;

What is the equivalent of this in JavaScript?

David G
  • 94,763
  • 41
  • 167
  • 253
Sam San
  • 6,567
  • 8
  • 33
  • 51

5 Answers5

3

Tertiary operator in JavaScript

Tertiary operators do exist in JavaScript:

var var1=".doc";
var var2=".docx";

alert(var1 ? var1 : var2);​

Proof: http://jsfiddle.net/gRMf2/

It will work as this (jsfiddle):

alert(var1 ? var1 : var2);​

Working with undefined variables

However, if var1 can be undefined, you will get an error (proof: jsfiddle). In such case writing this will solve the issue (proof: jsfiddle):

alert(typeof var1 !== 'undefined' ? var1 : var2);​
Tadeck
  • 132,510
  • 28
  • 152
  • 198
3

In javascript, var1 || var2 is same as php's var1 ? var1 : var2.

document.getElementById("file").innerHTML = "View file sent <a href='../folder/filename" + (var1 || var2);
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • In fact `var1 ? var1 : var2` is valid also in JavaScript. And there is one little difference: in PHP undefined first variable (like `$var1` in `$var1 ? $var1 : $var2`) will just be assumed false-ish, and will throw you a notice (if you will enable notices), while in JavaScript your script will just break. – Tadeck Aug 20 '12 at 01:54
2

JavaScript has no access to the file system. Even if it did, it would be the end-user's local file system. You will need to check that the file exists in PHP (or whatever server-side language you choose to use).

Brandon McKinney
  • 1,412
  • 11
  • 9
1

I'm not sure what you're doing here:

var1=".doc";
var2=".docx";

var1? var1 : var2;

This will always return ".doc" because var1 will always evaluate to true, regardless of whether you're using PHP or Javascript.


It sounds like you might be after something like this instead:
// this function is from http://stackoverflow.com/a/3646923/1188942
function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

var ext;
if (UrlExists("http://www.mywebsite.com/folder/file.doc"))
    ext = ".doc";
else
    ext = ".docx";
jeff
  • 8,300
  • 2
  • 31
  • 43
0

This is quite similar in Javascript:

var doc = ".doc";
var docx = ".docx";
var ext = doc ? doc : docx;
alert(ext);
Baiyan Huang
  • 6,463
  • 8
  • 45
  • 72