jQuery Data Type How to - Trim String on both ends using javascript








Question

We would like to know how to trim String on both ends using javascript.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var s = "\r\n\r\n\rHello\nWorld\n\r\n\r\n";
var trimmed = MyTrim(s);
document.writeln(trimmed);
function MyTrim(text) {<!--from w w  w  . j a  v  a2  s.  c  o  m-->
    var result = text + "";
    while (result.length > 0 && IsWhiteSpace(result[0]))
        result = result.substr(1, result.length - 1);
    while (result.length > 0 && IsWhiteSpace(result[result.length - 1]))
        result = result.substr(0, result.length - 1);
    return result;
}
function IsWhiteSpace(c) {
    return c == " " || c == "\r" || c == "\n";
}

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: