How to remove white space from the beginning and end of a string in JavaScript?

Method 1: using trim()
The trim() method returns the string stripped of white space from both ends. trim() does not affect the value of the string itself.

var str = "    hello, how are you?    ";
str.trim(); //hello, how are you?
Method 2: using regex
The expression '/^\s+|\s+$/g' removes white space from both sides of a string.

var str = "    hello, how are you?    ";
str.replace(/^\s+|\s+$/gm,''); //hello, how are you?
Method 3: using JQuery
The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these white space characters occur in the middle of the string, they are preserved.

$.trim("    hello, how are you?    "); //hello, how are you?
Final code and demo is here


No comments:

Post a Comment