Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

vuejs3 - A strange result about `parseStringStyle` in Vue3' s source code

I am studying Vue3 source code recently, one expression makes me really confusing

here it is:

  const propertyDelimiterRE = /:(.+)/;
  "color:red;".split(propertyDelimiterRE);//?["color", "red;", ""]

I

const propertyDelimiterRE = /:(.+)/;
const parseResult = "color:red;".split(propertyDelimiterRE);
console.log(parseResult)
question from:https://stackoverflow.com/questions/65880366/a-strange-result-about-parsestringstyle-in-vue3-s-source-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this is more of a split + regex question, but here it goes

The regular expression portion :(.+) has two parts, : and (.+)

: says to watch for the : character literally

(.+) says to capture any character(s) except for line terminators

so together, they will capture :red; (full match) and red; as the capture group.

The second part is that the way [split behaves] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#description)

When found, separator is removed from the string, and the substrings are returned in an array.

If separator is a regular expression with capturing parentheses, then each time separator matches, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

so togeter...

  • "color:red;".split( /:(.+)/) will use : and everything after it to split the string
  • that will be (sort of) equivalent of "color:red;".split(":red;)
  • which would return ["color", ""]
  • however, because we're using a split with capture group, it splices the matched capture group into the array, giving us ["color", ":red;", ""]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...