-2

I have an array with the following kind of strings:

var Nameslist = [];

Nameslist.push("home.mytest1.James Thomas 14-47");
Nameslist.push("home.mytest1.George Simon 7-2");
Nameslist.push("home.mytest1.Sandy Kylie 3-15");

Now I want to remove the first part of each string in the array. The array should look like this after removing home.mytest1.:

"James Thomas 14-47"
"George Simon 7-2"
"Sandy Kylie 3-15"

How can I do that?

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42

2 Answers2

1

Use map and replace

var Nameslist = [];

Nameslist.push("home.mytest1.James Thomas 14-47");
Nameslist.push("home.mytest1.George Simon 7-2");
Nameslist.push("home.mytest1.Sandy Kylie 3-15");

console.log(Nameslist.map(t=>t.replace("home.mytest1.", "")))
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
0

You could go with a string replace:

const nameList = [
  'home.mytest1.James Thomas 14-47',
  'home.mytest1.George Simon 7-2',
  'home.mytest1.Sandy Kylie 3-15'
];

const alteredNameList = nameList.map(value => value.replace('home.mytest1.', ''));

console.log(alteredNameList);

Or you can use a regular expression, if the thing you want to replace changes slightly:

const nameList = [
  'home.mytest1.James Thomas 14-47',
  'home.mytest2.George Simon 7-2',
  'home.mytest3.Sandy Kylie 3-15'
];

const alteredNameList = nameList.map(value => value.replace(/^home\.mytest\d+\./, ''));

console.log(alteredNameList);

The benefit of an expression is that you can determine if the portion you want to replace appears at the beginning, the end, or anywhere in-between.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132