简体   繁体   中英

How JavaScript regex work on this spinal case sentence

I have following JavaScript fucntion:

 function spinalCase(str) { str = str.replace(/([az])([AZ])/g, '$1 $2'); console.log(str); } spinalCase('thisIsSpinalTapIp');

Now it's showing me:

this Is Spinal Tap Ip

I can't understand how it identifies the space() and why it's using 2 regular expressions inside the replace function. Can you break it down please?

Note: the goal of this function is to get the spinal case sentence.

Let's break it down:

([az]) is matching a lowercase letter

([AZ]) is matching for an uppercase letter

/([az])([AZ])/g combine is matching for lowercase followed by an upperCase letter with the global flag that will match for all these occurrences.

When such occurrences are found they are getting replaced by $1 $2 (here $1 is group one lowercase letter and $2 is group 2 uppercase letter separated by a space).

Now let see how it work for thisIsSpinalTapIp

The above regex will match sI , sS , lT , and pI

and replace them with s I , s S , l T , and p I

so the string become this Is Spinal Tap Ip

This link will help you to visualize it regex

the regex parses every occurrance of a sequence of a lowercase and an uppercase letter, stores the lowercase one in $1 and the uppercase one in $2 ... then it replaces $1$2 with $1 $2 , eg inserts a space.

following match:

thi sIsS pina lT a pI p

so you'd have the collection ['sI','sS','lT','pI'] where the spaces will be added in between

You created two groups name $1 and $2 by parentheses in the RegEx. $1 and $2 refers to strings matched by those groups.

and those strings will replace $1 and $2 in the second parameter of String.replace.

every groups' name is like $Number, the number will increase by the sequence of parentheses in the Regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM