[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.


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

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