My initial problem was to store only the filename from the full path on an object and I did find the answers to that online but I had problem storing the same in a property of an object.
Here is a piece of code that I have written. Hopefully my problem would be clear.
let song = { name: document.getElementById('title').value,//Line 1 artist: document.getElementById('yr').value,//Line 2 path: function () {//Line 3 var filename = fullPath.replace(/^.*[\/]/, ''); return filename; }
This whole code is inside a function which is called and the user is asked to choose a file from his computer. Now what my problem is in Line3,I need to store the filename only from the fullpath (Example: ‘example.mp3’), inside the ‘path’ property of the object ‘song’. This is what was getting saved in ‘path’ once I run the code-
Please help me in solving this . Thanks!
Advertisement
Answer
You need to apply ()
to execute your function. But you can simplify it further by just assigning the value of your replace()
directly, like this:
let song = { name: document.getElementById('title').value,//Line 1 artist: document.getElementById('yr').value,//Line 2 path: fullPath.replace(/^.*[\/]/, '') };
If you’re committed to using the function in the way you defined it, you can do this:
let song = { name: document.getElementById('title').value,//Line 1 artist: document.getElementById('yr').value,//Line 2 path: function () {//Line 3 var filename = fullPath.replace(/^.*[\/]/, ''); return filename; }() };
Note the extra ()
after the path
function definition.