Trim spaces for String in JavaScript
The trim()
method returns a new string after removing the whitespace characters the beginning and the end of the original string.
Whitespace here refers to any one of these: space, tab, no-break space, etc., and also all the line terminator characters: LF, CR, etc.,.
'You are awesome ! '.trim(); //'You are awesome !'
' AWSM! '.trim(); //'AWSM!'
'AWSM '.trim(); //'AWSM'
Polyfill
You can use this polyfill script in your code before you use trim(), so that this code will create trim(), if it is not available in your JavaScript environment.
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
Last Updated on
Comments