简体   繁体   English

删除字符串中的第一个字符

[英]remove first character in string

i have this script which takes the input and adds "ay" to the end and i also need to delete the first letter of each string which doesnt work. 我有这个脚本,它接受输入并添加“ay”到最后,我还需要删除每个字符串的第一个字母,它不起作用。 I tried using .substring(1) but it didnt work. 我尝试使用.substring(1)但它没有用。

https://jsfiddle.net/kaibago/try07L8h/ https://jsfiddle.net/kaibago/try07L8h/

$(document).ready(function(){
    $("#button").click(function(){
        var input=$("input[name=checkListItem]").val();
        var toAdd=input.split(" ");
        for(var i=0;i<toAdd.length;i++){
            toAdd[i]+=toAdd[i][0]+"ay";
            //toAdd[i]=toAdd[0].substring(1); does not work supposed to delete first letter of each string//
        };
    var output=toAdd.join(" ");
    $(".list").append("<div class='item'>"+output+"</div>");
    });
});

You can use slice 你可以使用slice

$(document).ready(function(){
    $("#button").click(function(){
        var input=$("input[name=checkListItem]").val();
        var toAdd=input.split(" ");
        for(var i=0;i<toAdd.length;i++){
            toAdd[i]+=toAdd[i][0]+"ay";
            toAdd[i].slice(1);
        };
    var output=toAdd.join(" ");
    $(".list").append("<div class='item'>"+output+"</div>");
    });
});

subscript() isn't a function in JavaScript. subscript()不是JavaScript中的函数。 What you're looking for is substring() . 你要找的是substring()

toAdd[i] = toAdd[i].substring(1);

Working fiddle 工作小提琴

Your code work fine after changing two things. 更改两件事后,您的代码工作正常。

First : replace subscript() by substring() . 首先:substring()替换subscript() substring()

Second : 第二:

Instead of 代替

//e.g : input='abcd', this will return 'abcdaay' (Note double 'a')
toAdd[i]+=toAdd[i][0]+"ay";

Use : 采用 :

//e.g : input='abcd', this will return 'abcday'
toAdd[i]=toAdd[i]+"ay"; 

Because you don't need the [0] that select first character and also not use += in this case because you want to rewrite the value and not append first character to it. 因为你不需要[0]来选择第一个字符而且在这种情况下也不使用+=因为你想要重写值并且不向它添加第一个字符。

Full code : 完整代码:

$(document).ready(function(){
    $("#button").click(function(){
        var input=$("input[name=checkListItem]").val();
        var toAdd=input.split(" ");

        for(var i=0;i<toAdd.length;i++)
            toAdd[i] = (toAdd[i]+"ay").substring(1);

        $(".list").append("<div class='item'>"+toAdd.join(" ")+"</div>");
    });
});

Hope this helps. 希望这可以帮助。

substr方法应该可以帮到你。

toAdd[i] += (toAdd[i][0]+"ay").substr(1);

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

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