How to generate null characters when splitting strings in JavaScript _ javascript tips-js tutorial

Source: Internet
Author: User
When using the JavaScript split method to split strings, some null strings & quot; appear, especially when using regular expressions as separators. So why are these null strings generated? What should we do? This is the problem description we are going to discuss today.

When using the JavaScript split method to split strings, some null strings "" appear, especially when using regular expressions as separators.

Related Questions

Does the javascript Regular Expression generate an empty string group when grouping strings?

In the above question, when the subject uses a regular expression to separate strings, multiple empty strings "" are generated. The Code is as follows:

The Code is as follows:


'Step 4 asdf Weng Fen aa33 net s'. split (/([\ u4e00-\ u9fa5] {1})/gi );
// Output ["", "Zhang", "sdf", "4", "", "up", "", "Fa", "asdf ", "Weng", "", "Fen", "aa33", "Net", "s"]

So why are these null strings generated?

Problem Analysis

I searched on Google and found that there were not many results. Even if there were some, there was not much detailed explanation. I gave a rough description and then gave a link to the ECMAScript specification. It seems that if you want to know the real reason, you have to stick your head to the specifications.

Related Standards

Then, according to international practice, we should first go to the standard town building of ECMAScript.

The Code is as follows:


String. prototype. split (separator, limit)

This section describes the steps to execute the split method in detail. If you are interested, you can read it carefully step by step. Here, I will only explain the steps related to generating null strings, you are welcome to raise this question.

Procedure

Steps for extracting data:

The most important step in the whole process is step 1, which mainly performs the following tasks:
• Defines the values of p and q. The values of p and q are the same at the beginning of each loop (this step is outside the loop );
• Call the SplitMatch (S, q, R) method to split the string;
• Execute different branches based on different returned results. The main branch is branch III;
• Branch III is divided into eight small steps to fill the returned results in the pre-defined array.
• In this 8-step process, step 1 is used to return a substring of the original string. the start position is p (included) and the end position is q (not included ), note: An empty string is generated in this step. I mark it as a truncated string for reference below.
• Add the substring in the previous step to array
• The next few steps are to update related variables and continue the next cycle. (Step 7 is to save the capture group in the regular expression to array A, which is irrelevant to the generation of null strings)

SplitMatch (S, q, R)

Next, we need to know what the SplitMatch (S, q, R) method has done. This method is mentioned below the split specification. It mainly performs operations based on the separator Type:
• If the separator is of the RegExp type, call the internal method [[Match] of RegExp to Match the string. If the Match fails, return failure. Otherwise, return a MatchResult type result.
• If the separator is a string, the system returns a failure for matching and determination. If the separator fails, the system returns a MatchResult type result.

MatchResult

The above step introduces a variable of the MatchResult type. The document finds that this type of variable has two attributes: endIndex and captures. The value of endIndex is the position where the string matches and 1. captures can be understood as an array, when the Delimiter is a regular expression, the elements in it are the values captured by the Group. When the separator is a string, it is an empty array.

Next

We can see from the above steps that the split string is generated in the string truncation step (except for grouping and capturing of regular expressions ). It is used to intercept a string between the specified start (inclusive) and end position (excluded). When will it return? There is a special case where the value of the start position and the end position are equal. This is just a conjecture, because this specification does not provide a standard step for intercepting strings.

I 've been here. Why don't I take another step?

So I tried to search for some V8 source code to see if I could find a specific implementation method. Found the relevant code, source code Link

Here we extract some of them:

The Code is as follows:


Function StringSplitJS (separator, limit ){
...
...
// When the separator is a string
If (! IS_REGEXP (separator )){
Var separator_string = TO_STRING_INLINE (separator );

If (limit = 0) return [];

// ECMA-262 says that if separator is undefined, the result shocould
// Be an array of size 1 containing the entire string.
If (IS_UNDEFINED (separator) return [subject];

Var separator_length = separator_string.length;

// The separator is an empty string and the character array is directly returned.
If (separator_length = 0) return % StringToArray (subject, limit );

Var result = % StringSplit (subject, separator_string, limit );

Return result;
}

If (limit = 0) return [];

// When the separator is a regular expression, call StringSplitOnRegExp
Return StringSplitOnRegExp (subject, separator, limit, length );
}

// Some code is omitted here

I found in the code that the % _ SubString method is called to intercept the string when filling the array. Unfortunately, I did not find its definition, if you have any questions, please contact us. However, I found that the StringSubstring method corresponding to the substring method in JavaScript will call the % _ SubString method and return the result. If 'abc '. substring () returns "", indicating that the % _ SubString method returns "" When the start position and end position are the same.

So when will the start position be equal to the end position (q = p? I analyzed it step by step according to the above steps and found that:
• After the original string S matches the separator once, the next position of string S matches the separator. For example, 'abbbc '. split (' B '), 'abbbc'. split (/(B) {1 }/)
• One or more characters starting with a string match the delimiter. For example, 'abc'. split ('A'), 'abc'. split (/AB /)
• One or more character strings at the end of the string match the separator. The related step is step 1.
For example, 'abc'. split ('C'), 'abc'. split (/bc /)

In addition, when the regular expression is used as the separator, undefined may appear in the returned results.
For example, 'abc'. split (/(d )*/)

Let's look at the example at the beginning. Does it meet the above conditions?

Digress

This is the first time that I have carefully read the standards and norms of ECMAScript. The process is really painful, but after understanding it, I feel very happy. I would also like to thank the subject for asking this question and asking questions.
By the way, when a regular expression is used as a separator, The global modifier g is ignored, which is also an additional gain.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.