Examples JS trim method
We will see a different example of a trim() method.
Remove space both sides or one side of Single character.
<!DOCTYPE html> <html> <script> var str = " EyeHunts "; var st = str.trim(); document.write(st); </script> <body> </body> </html>
It will remove one side space only if only leading or the trailing spaces are in the string str.
2. trimLeft() only remove the left side space
<!DOCTYPE html> <html> <script> var str = " EyeHunts "; var st = str.trimLeft(); alert(st); </script> <body> </body> </html>
3. trimRight() only Remove Right side white space
Use it when wanting to remove extra spaces from the end of the string.
<!DOCTYPE html> <html> <script> var str = " EyeHunts "; var st = str.trimRight(); alert(st); </script> <body> </body> </html>
Answer: It’s very easy, you have to use replace() method. See the below code.
var str = "E H Y H U N T S"; str = str.replace(/ +/g, "");
Do comment if you know about any other use of the trim method in JS or have any doubts.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.