3 Example(s) of JavaScript trim function


Description :

JavaScript trim() is used to trim the spaces from left and right. In the below example, We have a string " Michael " which will be converted to "Michael" after trim function is applied. See the code snippet:


JavaScript trim function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<script>
var name="  Michael  ";
   document.write(name.trim());
</script>
</body>
</html>

Output

Description :

trimRight() remove the spaces from right side of the string but this is not a standard function so don't use this function on live websites because this will not work for every user because of incompatibilities. See the code snippet:


JavaScript trim function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<script>
var str = "   Welcome to LearnKode  ";
str = str.trimRight();
document.write(str);  //'  Welcome to LearnKode'  
</script>
</body>
</html>

Output

Description :

Example of trimLeft() : This is non standard function.


JavaScript trim function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<script>
var str = '   Welcome to LearnKode  ';
str = str.trimLeft();
document.write(str);  //'Welcome to LearnKode '  
</script>
</body>
</html>

Output