Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove characters from an strings array item in Javascript?

I have like this strings in array.

const x = [
  'a',
  ': 99999999999999999999999999,',
  ':',
  'this, is 2 :)'
]

How can I remove : and , from second element like this?

const x = [
  'a',
  '99999999999999999999999999',
  ':',
  'this, is 2 :)'
]

I tried replace : and , to ''. But there are these characters in other elements. And I don’t want to remove it. Also I tried startWith(‘:’), but it becomes all [undefined,undefined,undefined,undefined].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const v = u.map((x) => {
  x.startsWith(':') ? x.replace(':', '') : x;
});

console.log('v', v);

>Solution :

You are getting undefined values because you are not returning anything inside your .map() (common mistake, been there, done that). This would fix it:

const v = u.map((x) => {
  return x.startsWith(':') ? x.replace(':', '') : x;
});

// Or even shorter
const v = u.map((x) => (x.startsWith(':') ? x.replace(':', '') : x);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading