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. I tried using .substring(1)
but it didnt work.
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
$(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. What you're looking for is substring()
.
toAdd[i] = toAdd[i].substring(1);
Your code work fine after changing two things.
First : replace subscript()
by 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.
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);
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.