Home > Software design >  How can i make this code work properly, its based on a for-loop and is not completing its process
How can i make this code work properly, its based on a for-loop and is not completing its process

Time:12-08

for (let i = 0; i < ans.length; i  ) {
  ans = ans.replace(' ', ' ');
  ans = ans.replace('  ', ' ');
  ans = ans.replace('  ', ' ');
  //here ans is a value of an input.
}

Why is this stopping before completing the process?

CodePudding user response:

You are performing the same action in each iteration of the loop, so the loop is redundant in this code block. If you meant to replace all occurrences, a regex replacement is better:

ans = ans.replace(/ /g, ' ');
ans = ans.replace(/  /g, ' ');
ans = ans.replace(/\ \ /g, ' ');

If you are only targeting modern browsers, you can use replaceAll instead:

ans = ans.replaceAll(' ', ' ');
ans = ans.replaceAll('  ', ' ');
ans = ans.replaceAll('  ', ' ');

CodePudding user response:

Well based on the code I see you want to get rid of spaces no matter how many in a row, So I suggest Regular Expression :

let ans = "im an input here   so you can see the stuff"
ans = ans.replace(/\s /g , ' '); \* im an input here so you can see the stuff *\

How ever as it's been said on Wais Kamal Answer you can use replaceAll() as well for different cases

  • Related