javascript - How do I remove the first letter of every string in array with splice? - Stack Overflow

I have an array that contains multiple strings.I need to store each string minus the first letter and

I have an array that contains multiple strings. I need to store each string minus the first letter and then concatenate them into a sentence.

I am trying:

var missingFirstLetter = array[i].splice(1);

What I have found online guides me to believe this should work, but it doesn't work as intended.

I have an array that contains multiple strings. I need to store each string minus the first letter and then concatenate them into a sentence.

I am trying:

var missingFirstLetter = array[i].splice(1);

What I have found online guides me to believe this should work, but it doesn't work as intended.

Share Improve this question edited May 18, 2017 at 4:32 Andrew Li 58k14 gold badges134 silver badges148 bronze badges asked May 18, 2017 at 4:04 Rob HudsonRob Hudson 812 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You should slice (not splice!) each element of the array and then store it back into an array, which you can do with Array#map, which maps each element to a new value, in this case the string without the first letter:

var arrayNoFirstLetter = array.map(el => el.slice(1));

This will iterate through the array and map each element to a new string without the first letter and store the new array of strings into arrayNoFirstLetter. Make sure to use String#slice to get a section of a string, because there is not String#splice method. (maybe you mistook it for Array#splice?) Then you can use Array#join to join them with a delimiter (which is the string between each element when joined together):

var joined = arrayNoFirstLetter.join(""); //join with empty space for example

For example:

var array = ["Apples", "Oranges", "Pears"];
var arrayNoFirstLetter = array.map(el => el.slice(1)); // ["pples", "ranges", "ears"]
var joined = arrayNoFirstLetter.join(""); // "pplesrangesears"

Try this:

var a=["hHello","+-I-am","d-evil"];
var x;
var z="";
for(var i=0;i<a.length;i++){
x=a[i].substring(1);
z=z+x;
}
console.log(z);

Result is :

Hello-I-am-evil

Is it what you wanted?

var strings = ['string1', 'string2', 'string3'],
    stringsNoFirstCh = [];

for(key in strings){ // Iterates through each string in an array
   let string = strings[key];
   var s = string.substring(1); // Gets a string starting from index 1, so omits the first char
   stringsNoFirstCh.push(s); // Add to a new array: ['tring1', 'tring2', 'tring3']
}

var string = stringsNoFirstCh.join(''); // Transform to a string: tring1tring2tring3

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744937093a4602091.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信