How can I remove the first letter of every string in an array using splicing?

I have an array containing multiple lines. I need to keep each line minus the first letter and then concatenate them into a sentence.

I'm trying to:

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

      

What I found on the internet tells me that this should work, but it doesn't work as expected.

+3


source to share


3 answers


You have to slice (not spliced!) 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 a string without the first letter:

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

      

This will loop through the array and map each element to a new string without the first letter and store the new array of strings in arrayNoFirstLetter

. Make sure to use String#slice

to get the string section because there is no method String#splice

. (perhaps 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 joining 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"

      

+4


source


Is this 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

      

+1


source


Try the following:

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:

Hello-I-am-evil

      

+1


source







All Articles