In programming, trim (or strip) is a common string manipulation function which removes leading and trailing whitespace from a string. Precisely what constitutes whitespace varies between programming languages and implementations, but normally includes space, tab, line feed, and carriage return characters.
Using Loops:
function trim(str) { while (str.substring(0, 1) == ' ') { str = str.substring(1, str.length); } while (str.substring(str.length - 1, str.length) == ' ') { str = str.substring(0, str.length - 1); } return str; } Usage: var str = ' abc '; var trimmedStr = trim(str); OR
Using Regular Expressions
function trim(str) { return str.replace(/^\s+|\s+$/g,''); } Usage: var str = ' abc '; var trimmedStr = trim(str);
OR
Using an Object Oriented Approach
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } Usage: var str = ' abc '; // OR var str = new String(' abc '); var trimmedStr = str.trim();
|
No responses found. Be the first to respond and make money from revenue sharing program.
|