How to print a string in javascript

I want to check the return value of this function getFileExtension (input.files [0] .name) (I have a comment to point to this line) My question is how to print this value in javascript? Thanks!

<script> function getFileExtension(filename) { var ext=filename.split('.').pop(); return ext } </script> <input type='file' onchange="readURL(this);"> <script> function readURL(input) { if (input.files && input.files[0]) { if (getFileExtension(input.files[0].name)=="png") { // this line is our problem var reader = new FileReader(); reader.onload = function (e) { document.getElementById("pdf").innerHTML="<img id='blah' src=" + e.target.result + " alt='your image' width='450'>" } reader.readAsDataURL(input.files[0]); } } } </script> 
+6
source share
4 answers

You can print the values ​​in javascript by writing

 console.log(value); 

Most browsers have a console that you can see by pressing f12 . The values ​​will be there.

If you are using Internet Explorer, be sure to open the developer tools (f12) or you will receive an error message.

+6
source
 var msg = 'value: ' + yourVar; if (console) { console.log(msg); // or console.info(msg) or whatever } else { alert(msg); } 

Personally, I wrote a simple lightweight console so that I can output to any div on the page. I did this instead of a lot of document.write , as Avitus suggests in a comment.

0
source

I would use the Firebug plugin for Firefox for more detailed error descriptions and to see the values ​​connected to console.log (value)

0
source

You can do predefined tests so that your function produces the correct result in different situations:

 function test_getFileExtension() { test("foo.png", "png"); test("bar.py", "py"); test("the_really_long_name.txt", "txt"); test("playlist.xspf", "xspf"); test("%20.txt", "txt"); test("file_without_extension", ""); // actually gives an error function test(input,output) { var o=getFileExtension(input); if (o === output) { console.log("OK: "+input+" --> "+o); } else { console.log("ERROR: "+input+" --> "+o); } } } 

Then, as soon as you update your function, you call test_getFileExtension() again and make sure that it still works as intended.

0
source

Source: https://habr.com/ru/post/949155/


All Articles