Thursday, July 3, 2014

Trim a String in JavaScript

Enter a string with spaces in front and back and press Trim String button<br> <br>
String: <input id="foo" type="text" value="   a quick brown fox jumps over  ">
<button onclick="trim()">Trim String</button>
<script>
if (!String.prototype.trim) {
   String.prototype.trim=function() {
    return this.replace(/^\s+|\s+$/g, '');
   };
}
function trim() {
    var foo = document.getElementById("foo").value;

    alert("(" + foo.trim() + ")");
}
</script>

No comments:

Post a Comment