Question

What would be the effect of the following line

somestring.trim().split(/\s*,\s*/);

in javascript??

I thought it would split at comas with any number of spaces before or after.

But from what i have learned the regex would be like

\\s*,\\s*

.I am confused

Was it helpful?

Solution

I thought it would split at comas with any number of spaces before or after.

That is correct. It will even match commas with no spaces before and after.

The / before and after is just a syntax that some regex parsers uses as a delimiter for the regex expression.

In Javascript you should use split('string') (apostrophes) for splitting on strings or characters, and split(/regexp/) (slashes) for splitting on regex expressions.

The double backslash (\\) is used to escape special characters in strings so that e.g. '\n' is interpreted as a single line-feed character while '\\n' is interpreted as a backslash and an "n" ('\n').

When using the regex delimiters / on your expression, you don't have to escape special characters as the parser knows it's a regex.

split(/\s*,\s*/) // No escaping needed with backslash delimiters.

OTHER TIPS

I thought it would split at comas with any number of spaces before or after to the comas.

So here is example:

'so me          ,                    s t r i n g'.trim().split(",");

I Am using just trim with coma here it divide the string into two parts but the first element contains space at the end. And the second element contains space at Begin.

Result will be

["so me          ", "                    s t r i n g"]

For Above expression

'so me       ,                s t r i n g'.trim().split(/\s*,\s*/);

I Am using trim with (/\s*,\s*/); Here It divide the string into two parts but no space at starting of second element and ending of first element.

Result is

["so me", "s t r i n g"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top