[JS practice] javascript prototype Trim a String(重写trim方法)

Title :
Trim a String(重写javascript中的trim方法)

Description :
Extend the String prototype by a trim function, that returns the string with leading or trailing whitespaces removed.

重写javascript中的trim方法,使它可以消除一个字符串左右两边的空格(字符串中间的空格不用被消除)。

PS: Of course, the original trim function was removed before 😉

Best solution :

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "");
};

Or we could use the basic function which will remove the right and left whitespaces.

String.prototype.trim = function() {
  return this.trimLeft().trimRight();
};

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s