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.
The expression '/^\s+|\s+$/g' removes white space from both sides of a string.
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.
Demo
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? ";Method 2: using regex
str.trim(); //hello, how are you?
The expression '/^\s+|\s+$/g' removes white space from both sides of a string.
var str = " hello, how are you? ";Method 3: using JQuery
str.replace(/^\s+|\s+$/gm,''); //hello, how are you?
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
Demo
No comments:
Post a Comment