user11729404
user11729404

Reputation:

How do I replace single character in item in array?

I have been dabbling this problem for a bit, and I am very confused. So I have this array names = ["Fern","Alexa","Constance","Daniella","Connie","Flora","Hannah","Maddie"];

and I want to change the first letter of the first name to 'b' and then return the whole thing, without completely destroying the names for Ex: instead of "Fern", it would be "Bern"

Can someone please assist. I have tried on my own many different methods and strategies, I can't figure it out. Please assist.

Thank You

Upvotes: 1

Views: 559

Answers (4)

iAmOren
iAmOren

Reputation: 2804

You said you only want to change the first letter of the first name without changing the original names array.

First, clone the array: namesClone=names.slice().
If you don't use slice, both names and namesClone with be different variable names with the same data, so change to either will effect the other.

Access first name and set it to "B" + the rest: namesClone[0]="B"+namesClone[0].slice(1).
slice(1) returns everything from char 1 to end, without char 0 (in your example, "F").

names is not changed.

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Using map, slice and template string

const data = ["Fern","Alexa","Constance","Daniella","Connie","Flora","Hannah","Maddie"];

const update = (arr, char) => arr.map(str => `${char}${str.slice(1)}`);

console.log(update(data, 'B'));

Upvotes: 0

sonEtLumiere
sonEtLumiere

Reputation: 4572

Iterate with for of loops to access each item and then apply replace method.

var names = ["Fern","Alexa","Constance","Daniella","Connie","Flora","Hannah","Maddie"];
var newNames = [];

for(let el of names) {
  newNames.push(el.replace(el[0], 'B'));
}

console.log(newNames);

Upvotes: 0

Sudhanshu Kumar
Sudhanshu Kumar

Reputation: 2044

This should work.

let names = ["Fern", "Alexa", "Constance", "Daniella", "Connie", "Flora", "Hannah", "Maddie"];

let modified = names.map(e => e.replace(e[0], 'B'))

console.log(modified);

Upvotes: 1

Related Questions