What is the splitting logic of the string split method in javascript?

"aaabbbcccdeefff".split(/(\w)\1+/)
The output of

this code is:

["", "a", "", "b", "", "c", "d", "e", "", "f", ""]

but:

"aaabbbcccdeefff".replace(/(\w)\1+/g,"")

output result is

"d"

so as I understand it, the split result should be:

[d]
What"s wrong with

?

May.08,2021

The regular expression of

as a split parameter if the packet is captured, the captured result will be spelled in the result array.
so there will be a parallelbmeme cmeme in the result. Because they are the result of (\ w) capture, and "" is because the delimiter appears at the beginning or end of each iteration, it produces a " character.

if you want to achieve the desired output [d] , you can do this:

"aaabbbcccdeefff".replace(/(\w)\1+/g, '').split('')

if you want to achieve the kind you understand, you can do this "aaabbbcccdeefff" .replace (/ (\ w)\ 1purchase answer g, ""). Split ("");


replace must first return a string, according to the es5 specification

clipboard.png

the end result is a string. The first floor is right. Only after split can the result of [d] be

. The

string call replace returns a string, of course. String.prototype.replace ()
string call split returns the split array. The String.prototype.split ()


string is replaced with replace and becomes an array. I'm afraid he's crazy


"aaabbbcccdeefff".split(/(\w){1+}/)

// =>["aaabbbcccdeefff"]
Menu