简体   繁体   中英

using replace to remove part of url

my issue: i need to remove part of the directory to be able to use as url in a for loop setup.

php file

header('Content-type: application/json');

echo json_encode(array(
    "name" => "website",
    "type" => "folder",
    "path" => $dir,
    "items" => $response
));

i have two functions path which is usr/www/account/website/folder1/img.png paths with replace function should be /folder1/img.png am receiving error as undefined when its in a For loop but works fine without the loop, what am i doing wrong?

if(scannedFiles.length) {

                scannedFiles.forEach(function(f) {
                    var paths = f.path.replace('usr/www/account/website', '');

                    var file = $('<li class="files"><a href="'+ f.paths +'" title="'+ f.paths +'" class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></a></li>');
                    file.appendTo(fileList);
                });

            }

"f.paths" is unnecessary since its a local variable and is not extracted from an array so by changing it to "paths" it works

var file = $('<li class="files"><a href="'+ f.paths +'" title="'+ f.paths +'" class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></a></li>');

In your code, f.paths is undefined , you either need to used paths which is the replacement for f.path or use f.path , which is the original file path.

"f" in the below code refers to each item in the scannedFile and as you are trying to access f.paths will give the value if paths is a property of that object. If paths is not a property it gives you undefined.

You can modify your code as below

    if(scannedFiles.length) {    
                scannedFiles.forEach(function(f) {    
                    let replacedPath = f.path.replace('usr/www/account/website', '');

                    let file = $('<li class="files"><a href="'+ replacedPath +'" title="'+ replacedPath  +'" class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></a></li>');
                    file.appendTo(fileList);
                });

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM