PDA

View Full Version : What is this?


pankajjain15
12-08-2008, 01:45 AM
str.replace(/^\s+|\s+$/g, '');

I am using this function in my javascript file .

I found it some other forum . but don't know what it means?

will you please briefely explain me in detail.

thanks.

rangana
12-08-2008, 02:32 AM
That snippet removes whitespaces from the end and beginning of the string.

The replace function could accepts two arguments:

The first one is the "find string" which could accept RegularExpression (the one you've pointed is a RegExp).

...and the 2nd argument is the "replace string".


The first agrument, says:
/^\s+|\s+$/g .
- This means:

/ - Start of the Regular Expression
^ - Find a match from the start of the line
\s - matches space + - matches one or more of them
| - OR switch
$ - Find a match at the end of the line
/ - End of the regular expression
g - Global pattern matching. This matches the element from the start till the end. Otherwise, it would stop when finding a first match.


To translate, the regular expression says:
Find one or more spaces at the start of the line, also/or one or more spaces at the end of a line and replace it with '' (which is an empty string).

Hope that makes sense.

For further reading::
http://www.regular-expressions.info/
http://www.w3schools.com/jsref/jsref_replace.asp