简体   繁体   English

动态字符串中的Javascript切片字符

[英]Javascript slice character from dynamic string

I am trying the remove the last four characters of each dropdown item in a dynamic file list. 我正在尝试删除动态文件列表中每个下拉项的最后四个字符。

I have tried to use javascript spice syntax after reading this thread , but it seems to remove the full string of the other item in the list rather than just characters. 在阅读此线程后 ,我尝试使用javascript spice语法,但似乎删除了列表中其他项的完整字符串,而不仅仅是字符。 list = list.slice(0, -1);

I'm not sure what is wrong with my approach. 我不确定我的方法有什么问题。

function load_list() {
            $("#filename").empty();
            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: "/cgi-bin/list_cgi?action=get_list",
                success: function(result) {
                    var list = result.file.sort();
                    var current = result.current.split("/").pop();
                    list = list.slice(0, -1);
                    if (list.length == 0) {
                        $("#unavailable").html("<h2>File not found, please upload.</h2>");
                        show_upload();
                        return;
                    }
                    for (var i in list) {
                        $("filename").append("<option>" + list[i] + "</option>");
                                            }
                    $("filename").val(current);


                }
            });
        }

try this 尝试这个

    $.each(list,function(i){
  list[i].slice(0, -4);
});

assuming you have sorted files into list object .. 假设您已将文件分类到列表对象中。

or just replace your code 或只是替换您的代码

for (var i in list) {
                    $("filename").append("<option>" + list[i] + "</option>");
                                        }

with

$.each(list, function(i){
list[i] = list[i].slice(0,-4);
$("filename").append("<option>" + list[i] + "</option>");
})

You are slicing an Array and not a string. 您正在切片数组而不是字符串。

Try to use slice in this loop instead. 尝试在此循环中使用切片。

for (var i in list) {
                        list[i] = list[i].slice(0, -4); //remove last 4 characters
                        $("filename").append("<option>" + list[i] + "</option>");
              }

Update: answering the comment, 更新:回答评论,

You can use 您可以使用

for (...) {
        // use value attribute to ensure that the value is used in its entirety.
        $("filename").append("<option value='" + list[i] + "'>" + list[i].slice(0, -4) + "</option>");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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