0

function removeExtraSpace(input) {
  const pattern = /(?:<p><br><\/p>)+$|(<p> *<\/p>)+$/g;
  while(pattern.test(input.trimEnd()) == true){
      input = input.trimEnd().split(pattern)[0]
  }
  return input;
}

console.log(removeExtraSpace("<p>test</p><p>test2</p><p><br></p><p><br></p><p></p><p> </p><p>  </p> "));

Input example:

"<p>test</p><p>test2</p><p><br></p><p><br></p><p></p><p> </p><p>  </p> "

Expected output:

"<p>test</p><p>test2</p>"

Returns:

"<p>test</p><p>test2</p><p><br></p><p><br></p><p></p><p> </p>"

But if I add a console log to my loop, it starts to work. What am I bastardizing here?

function removeExtraSpace(input) {
  const pattern = /(?:<p><br><\/p>)+$|(<p> *<\/p>)+$/g;
  while(pattern.test(input.trimEnd()) == true){
      input = input.trimEnd().split(pattern)[0]
      console.log(pattern.test(input.trimEnd()))
  }
  return input
} 

console.log(removeExtraSpace("<p>test</p><p>test2</p><p><br></p><p><br></p><p></p><p> </p><p>  </p> "));
jabaa
  • 5,844
  • 3
  • 9
  • 30
faradh'im
  • 1
  • 1
  • 2
    You don't appear to be returning anything... – Shadow Jun 28 '22 at 23:43
  • @Shadow Thanks for pointing that out. While moving the code, I was removing another console log at the end above my return and took the return with it – faradh'im Jun 28 '22 at 23:47
  • 2
    You're calling `pattern.test(input.trimEnd())` in `console.log`. A global regex has a state and stores the position of the last match. You can remove the `console.log` and only call `pattern.test(input.trimEnd())` with the same result. – jabaa Jun 28 '22 at 23:48
  • Or better [javascript string exec strange behavior](https://stackoverflow.com/questions/2807670/javascript-string-exec-strange-behavior). There are probably many more and better duplicates, but these two were the best I've found. – jabaa Jun 28 '22 at 23:53

0 Answers0