Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace words in a string from an array of string [duplicate]

i receive a string that i want to clean from some word, i tried to make a function for that but it doesn't work :

export const cleanArrondissements = async (city) => {

  const arrondissements = [ 'Arrondissement', 'arrondissement', '1er','2e','3e', '4e', '5e', '6e', '7e', '8e', '9e', '10e','11e','12e','13e','14e', '15e', '16e', '17e', '18e', '19e', '20e']
  arrondissements.forEach(element => {
    city.replace(element, '')
  });
  return city;

}

what would be the best way to do that ?

like image 680
yoyojs Avatar asked Feb 17 '26 02:02

yoyojs


1 Answers

replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced

so with replace you don't change element.You need to assign to your variable to accept replace method's changes.

export const cleanArrondissements = async (city) => {   
  const arrondissements = [ 'Arrondissement', 'arrondissement', '1er','2e','3e', '4e', '5e', '6e', '7e', '8e', '9e', '10e','11e','12e','13e','14e', '15e', '16e', '17e', '18e', '19e', '20e']
  arrondissements.forEach(element => {
    city=city.replace(element, '')
  });
  return city;
}

if you may have more than one same element in base string then you can use regex

city=city.replace(new RegExp(element, 'g'), '')
like image 88
mr. pc_coder Avatar answered Feb 19 '26 16:02

mr. pc_coder