/

HTML / CSS / JavaScript Tutorial

JavaScript String method: trim()

[this page | pdf | back links]

The trim() method (when applied to a JavaScript string) returns a string with whitespace (i.e. spaces) removed from start and finish of string.

 

It has the following syntax (with no parameters):

 

string.trim()

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var y = "  ab  "
document.getElementById("Example").innerHTML =
  'var y = "<span style="white-space: pre;">' + 
  y + '</span>";<br>' +
  'var x = y.trim();';
document.getElementById("Result").innerHTML = y.trim();
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodStringTrim() {
  var z = "abc"; return !!z.trim;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript String Variables


Desktop view | Switch to Mobile