javaScript Properties and Methods: String.prototype.trim()

javaScript Properties and Methods: String.prototype.trim()

Image for postDEVDOJO course on javaScript Basics

The trim() method is used to remove white space and from both ends of a string (white space meaning characters like space, tab, no-break space and so on). It also removes line terminator characters such as carriage return (CR) and line feed (LF).

SYNTAX:

str.trim()

where str is the string which will be returned stripped of white space from both ends.

In this instance, we shall strip the string ? java ? of its white space;

var init = ? java ?;

console.log(init.trim()); // logs ?java?

To crosscheck (It?s alright to feel something isn?t right :)):

var initShort = init.trim();

console.log(init.length()); // logs 6, one white space on each side

console.log(initShort()); // logs 4, no white space

Sometimes str.trim() may not be natively available (not implemented specifically). If that?s the case, to use str.trim(), we would have to run this little snippet of code before any other code.

if (!string.prototype.trim) {

String.prototype.trim = function() {

return this.replace(/^[suFEFFxAO] + |[suFEFFxAO] + $ /g, ? ?);

};

}

In addition to str.trim(), two ?sub-methods?, str.trimLeft() and str.trimRight() which (as you might have guessed) removes white space from the left and right ends of a string respectively. Although both are supported on Chrome, Edge and Firefox, they are recognized as non-standard and shouldn?t be used on production sites as they will not work for every user.

Browser Compatibility:

Desktop Browsers such as Chrome, Edge, Firefox(3.5 (1.9.1)), Internet Explorer 9, Opera 10.5 and Safari 5 support str.trim()

Mobile Browsers: Most browsers on mobile platforms support str.trim()

NOTE: str.trim() can only be used to remove white space before and after a string, to remove white space between the string, we would have to be a bit more creative and use str.split(? ?). join(??)

An Example: var initials = ?R C?;

var newInitials = initials.split(? ?).join(??);

console.log(newInitials); // logs ?RC?

17

No Responses

Write a response