JavaScript split split string

 JavaScript's split function can be used to cut strings and execute according to the set cutting point. It can cut each text, cut according to spaces, cut according to a certain punctuation, etc. After the editors test, in addition to English letters, JavaScript Split can also cut the content of Traditional Chinese smoothly. If you want to do some string comparison and other actions, split can come in handy.


JavaScript split basic syntax

string.split (specify the cut point, the maximum number of cuts)


The string is the string to be cut. The first parameter in the split brackets, "Specify the cut point" is a required item, telling JavaScript where to start cutting the string. The common usage is to use double quotation marks. As for The second parameter "maximum number of cuts" is an optional item to tell JavaScript how many parts to cut at most. If it is not filled in, JavaScript split will cut the entire string completely according to the first parameter.

JavaScript split example one

<script type="text/javascript">
 var string="Good morning to you.";
 document.write(string.split("") + "<p>"); // Cut according to each character and output Result: G,o,o,d, ,m,o,r,n,i,n,g, ,t,o, ,y,o,u,.
 document.write(string.split(" ") + "<p>"); // Cut according to each space, output result: Good, morning, to, you.
 document.write(string.split(" ",3)); // Cut according to each space, only Cut out 3 parts and output the result: Good, morning, to
</script>

The first designated cut is written as two double quotation marks connected together, which means to cut according to each character, so the output result is separated by one character, and even a space is considered as one character. The second The specified cutting point is separated by double quotation marks, which means cutting the string according to each space, so the output result is each separated word. The third specified cutting point is the same as the second, but as long as three parts are cut out, So the output result is only the first three words.

JavaScript split example two

<script type="text/javascript">
 var string = '1234567';
 var NewArray = new Array();
 var NewArray = string.split("4");
 document.write("The first block cut out Yes" + NewArray[0] +'<br>');
 document.write("The second block cut out is" + NewArray[1]);
</script>

In the second example, we cut the string "123456789" from "4" with the split function and store it in the array, and then output the two parts of the array through document.write .

Post a Comment

0 Comments