3

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 ?

yoyojs
  • 1,723
  • 5
  • 24
  • 41
  • 2
    Please go read the description of how `replace` works _carefully_. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – CBroe Jul 20 '20 at 13:00
  • 6
    `.replace()` returns a new string, you need to assign the string returned by `.replace()` to `city` variable ---> `city = city.replace(element, '')` – Yousaf Jul 20 '20 at 13:00
  • hopefully the word only appears once in the string. – epascarello Jul 20 '20 at 13:13

2 Answers2

2

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'), '')
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
1

Reduce makes it cleaner:

const cleanArrondissements = (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']
      
      return arrondissements.reduce((acc, cur) => acc.replace(cur, ""), city);
}
Ravi Kukreja
  • 627
  • 1
  • 8
  • 17