How can I split a string like this
var str = "M50 0 L0 100 L100 100 L50 0 z M0 0 L100 0 L50 100 L0 0 Z";
var arr4String = str.split('z|Z');
I'm expecting to get an array with 3 elements:
["M50 0 L0 100 L100 100 L50 0", "M0 0 L100 0 L50 100 L0 0", ""]
To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.
The JavaScript split() method is used to split up a string into an array of substrings.
Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.
To split a number into an array: Convert the number to a string. Call the split() method on the string to get an array of strings. Call the map() method on the array to convert each string to a number.
Use regex. Using the g
flag says search the entire string from beginning to end so that it doesn't stop the first time it hits a z|Z
. The i
flag makes the search case-insensitive.
var str = "M50 0 L0 100 L100 100 L50 0 z M0 0 L100 0 L50 100 L0 0 Z";
var arr4String = str.split(/z/gi);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With