I was looking for a trim function in JavaScript which doesn’t exist and some code on Googling suggests that use:
function trimStr(str) {
return str.replace(/^\s+|\s+$/g, '');
}
I want to know how str.replace(/^\s+|\s+$/g, '')
works. I understand that this is some form of regular expression but dont know what it is doing.
/^\s+|\s+$/gsearches for whitespace from either the beginning or the end of the string. The expression can be split into two parts,^\s+and\s+$which are separated by|(OR). The first part starts from the beginning of the string (^) and includes as many whitespace characters it can (\s+). The second part does the same but in reverse and for the end using the dollar sign ($).In plain english, the regular expression would go like this:
Note that
\smatches spaces, tabs and line breaks.The
/gpart at the end enables global searching, which allows multiple replacements (eg. not just the beginning, but the end of the string also).