最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论