-1

I have an Array:

arr1 = ["gbt100", "gbt1130", "gbt12300", "gbt104230"]

How can I remove the "gbt" string from each of the elements?

5
  • Please read the docs on Array methods. What have you tried? Commented May 21, 2018 at 8:55
  • arr1.join(',').replace(/gbt/g, '').split(',') Commented May 21, 2018 at 8:57
  • I've read about the foreach and filter methods. I just don't know how to apply it. Commented May 21, 2018 at 8:58
  • @PAyTEK You want to create a new array with the same elements of the old array, but transformed in a way. This means you need map, not filter, not forEach. Commented May 21, 2018 at 9:00
  • Ok, Thanks @Xufox! Commented May 21, 2018 at 9:25

2 Answers 2

8

You can use the map method by passing a callback function as an argument which is applied for every item from your given array.

Also, you need to use replace method in order to remove the gbt string.

arr1 = ["gbt100", "gbt1130", "gbt12300", "gbt104230"]
arr1 = arr1.map(elem => elem.replace("gbt", ""));
console.log(arr1);

Another approach is to pass a regex as the first argument for the replace method.

arr1 = ["gbt100", "gbt1130", "gbt12300", "gbt104230"]
arr1 = arr1.map(elem => elem.replace(/gbt/g, ""));
console.log(arr1);

If you want to remove all the alphabetical chars just change the regex expression inside replace method.

arr1 = arr1.map(elem => elem.replace(/[a-zA-Z]/g, ""));
Sign up to request clarification or add additional context in comments.

7 Comments

@Xufox, what if array is like gbt567, abg455, ytu456 ?
@akhilaravind you mean to remove all alphabetic characters then use [a-zA-Z] instead of gbt to replace all alphabets
@akhilaravind Don't make up scenarios OP hasn't asked for, otherwise you end up answering questions nobody asked. If OP states the values to remove could be different and gives the exact specifications, then we can tailor solutions around it. Otherwise your scenario is out of scope.
@Nagaraju i have answered below
@xufox yes I was correcting that
|
-1

You can try Array.Map and for each of the item using substring

const arr1 = ["gbt100", "gbt1130", "gbt12300", "gbt104230"]

const newArr = arr1.map(x=>x.substring(3, x.length))

console.log(newArr)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.