JavaScript String trim() Method | js trim
Example1Removespaceswithtrim():lettext=" HelloWorld! ";letresult=text.trim();TryitYourself»[1]Removespaceswithreplace()usingaregularexpression:lettext=" HelloWorld! ";letresult=text.replace(/s+|s+$/gm,);TryitYourself»[2]DefinitionandUsageThetrim()methodremoveswhitespacefrombothsidesofastring.Thetrim()methoddoesnotchangetheoriginalstring.SyntaxParametersReturnValueTypeDescriptionAstringAstringwithremovedwhitespacefrombothends.BrowserSupporttrim()isanECMAScript5(ES5)featu...
Example 1Remove spaces with trim():
let text = " Hello World! ";let result = text.trim();
Try it Yourself »[1]Remove spaces with replace() using a regular expression:
let text = " Hello World! ";let result = text.replace(/s+|s+$/gm,);
Try it Yourself »[2] Definition and UsageThe trim() method removes whitespace from both sides of a string.
The trim() method does not change the original string.
Syntax Parameters Return Value Type Description A stringA string with removed whitespace from both ends. Browser Supporttrim() is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome Edge Firefox Safari Opera IE Yes Yes Yes Yes Yes 9-11 References Try it Yourself » (www.w3schools.com) Try it Yourself » (www.w3schools.com)