1

I have a STRING and I want to replace some character, and this characters are in an array. Here is my code :

let arrayParam = [];
arrayParam.push('X');
arrayParam.push('Y');
arrayParam.push('Z');

let stringToFilter = 'Y0000000';

let stringFiltered;

for (let i = 0; i < arrayParam.length; i++) {
  stringFiltered = stringToFilter.replace(arrayParam[i], '');
  console.log(`array:${arrayParam[i]}     stringFiltered:${stringFiltered}`);
};

This result in the console :

element:A     stringFiltered : Y0000000
element:B     stringFiltered : 0000000
element:C     stringFiltered : Y0000000

I don't understand, my var is declared outside the loop why it doesn't remember the change ?

2
  • you are not updating the value of the variable stringToFilter, it is always 'Y0000000', update it to the same value of stringFiltered Commented Sep 1, 2020 at 19:17
  • The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. so "Y00..".replace("X"," ") return Y00... Commented Sep 1, 2020 at 19:23

2 Answers 2

2

You also need to update the stringToFilter.

for(let i=0 ; i < arrayParam.length; i++ ) {
  stringFiltered = stringToFilter.replace(arrayParam[i], '');
  console.log(`array:${arrayParam[i]}  stringFiltered:${stringFiltered}`);
  stringToFilter = stringFiltered;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The result is what you'd expect, in the last iteration stringFiltered is being updated to:

"Y0000000".replace("Z", '');

which results in "Y0000000".

A nicer way to achieve what you're trying would be:

const regex = new RegExp(arrayParam.join('|'), 'g');
stringFiltered = stringToFilter.replace(regex, '');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.