Brandon - Free Palestine
Brandon - Free Palestine

Reputation: 16656

What does this JS do?

var passwordArray = pwd.replace(/\s+/g, '').split(/\s*/);

I found the above line of code is a rather poorly documented JavaScript file, and I don't know exactly what it does. I think it splits a string into an array of characters, similar to PHP's str_split. Am I correct, and if so, is there a better way of doing this?

Upvotes: -1

Views: 316

Answers (3)

KooiInc
KooiInc

Reputation: 122906

It does the same as: pwd.split(/\s*/).

pwd.replace(/\s+/g, '').split(/\s*/) removes all whitespace (tab, space, lfcr etc.) and split the remainder (the string that is returned from the replace operation) into an array of characters. The split(/\s*/) portion is strange and obsolete, because there shouldn't be any whitespace (\s) left in pwd.

Hence pwd.split(/\s*/) should be sufficient. So:

'hello cruel\nworld\t how are you?'.split(/\s*/)
// prints in alert: h,e,l,l,o,c,r,u,e,l,w,o,r,l,d,h,o,w,a,r,e,y,o,u,?

as will

'hello cruel\nworld\t how are you?'.replace(/\s+/g, '').split(/\s*/)

Upvotes: 1

gion_13
gion_13

Reputation: 41533

it replaces any spaces from the password and then it splits the password into an array of characters.

It is a bit redundant to convert a string into an array of characters,because you can already access the characters of a string through brackets(.. not in older IE :( ) or through the string method "charAt" :

var a = "abcdefg";
alert(a[3]);//"d"
alert(a.charAt(1));//"b"  

Upvotes: 2

JaredPar
JaredPar

Reputation: 754585

The replace portion is removing all white space from the password. The \\s+ atom matches non-zero length white spcace. The 'g' portion matches all instances of the white space and they are all replaced with an empty string.

Upvotes: 0

Related Questions