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 ?

3
  • 2
    Please go read the description of how replace works carefully. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 20, 2020 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, '') Commented Jul 20, 2020 at 13:00
  • hopefully the word only appears once in the string. Commented Jul 20, 2020 at 13:13

2 Answers 2

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'), '')
Sign up to request clarification or add additional context in comments.

Comments

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);
}

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.