-1

So i have a string which is "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and i am trying to remove the unnecessary tabs and new lines.

I have tried using .replace(/(\n\t)/g, '') to replace the \n and \t but it doesn't seem to replace anything. I have been using https://regexr.com/ to help try and understand how to replace \n and \t but i am having no luck. Is it because "\n\n\t\t\t\t" is joined with "10-pack" that i am unable to remove \n and \t?

Any help would be much appreciated as regular expression is not my strong point.

  • 1
    If your string contains new-line symbols and tab symbols (and not literal `\n` and `\t`) you can use `/[\n\t]+/g` – markalex Mar 29 '23 at 18:54

2 Answers2

1

Your regex looks for tab immediately following newline, and it founds only one such pair and replaces it. To replace any of tabs or newlines you should use symbol classes instead of groups:

"BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes".replace(/[\n\t]+/g,'')
//Output: "BALCONI 10-pack MixMax chocolade cakejes" 
markalex
  • 8,623
  • 2
  • 7
  • 32
0

As you want to match multiple instances, you must tell regex to do so. You can do this by using: /([\n\t]*)

This says match \n or \t at least zero or more times

Agyss
  • 160
  • 1
  • 15
  • There's no need for double backslashes - the string clearly contains `\n` so we can just replace that, without double backslashes. – Ar Rakin Mar 29 '23 at 18:55
  • As OP uses regular expression literal and not string, there is no need to escape `\\` – markalex Mar 29 '23 at 18:57
  • Thanks, I was too fast on this one and of course you are right - adapted my anwer. – Agyss Mar 29 '23 at 19:03