Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: split by this|that

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", ""]
like image 275
thednp Avatar asked Feb 12 '16 23:02

thednp


People also ask

How do you split a JavaScript expression?

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.

Is there a split in JavaScript?

The JavaScript split() method is used to split up a string into an array of substrings.

Can split take multiple arguments JS?

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.

How do you split a number in JavaScript?

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.


1 Answers

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);
like image 123
Jordan Mulder Avatar answered Oct 27 '22 00:10

Jordan Mulder