-3

How to remove white space from start and end, also I would like to remove the character "\n" and "\t" by Regex. I only able to remove the white space like this way replace(/^\s+|\s+$/g,'')

" My name is\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tRashel. "

Thanks in advance

2 Answers2

1

No need for a fancy regex. Just simply trim the string and then replace all sequences of consecutive white-space characters with a single space. Without more examples, this should work best.

const input = '   My name is\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tRashel.   ';

output.value = input.trim().replace(/\s+/g, ' ');
<textarea id="output" rows="2" cols="20"></textarea>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

To remove the whitespace from the start and end of strings, you can use trim() on the strings, like this:

stringName = stringName.trim();

This is also illustrated here.

To remove all line breaks and tabs in a string, you can use this regex /(\r\n|\n|\r)/gm, like this:

someText = someText.replace(/(\r\n|\n|\r)/gm, "");

This is also illustrated here.