开发者

What does this JS do?

开发者 https://www.devze.com 2023-02-23 07:32 出处:网络
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
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_spl开发者_运维知识库it. Am I correct, and if so, is there a better way of doing this?


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"  


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*/)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消