Javascript: split by this | that

How can I break a line 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 expect to get an array with three elements:

 ["M50 0 L0 100 L100 100 L50 0", "M0 0 L100 0 L50 100 L0 0", ""] 
+6
source share
6 answers

Use regex. Using the g flag, the entire line is searched from beginning to end so that it does not stop when it first accesses 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); 
+3
source

If you want to split into a regular expression, you need to pass the regular expression to split as a parameter:

 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/); ^ ^ 

It produces:

 ["M50 0 L0 100 L100 100 L50 0 ", " M0 0 L100 0 L50 100 L0 0 ", ""] ^ ^ ^ 

(note the extra spaces, as the regex does not remove them).

If you want to trim the results, you can use:

 ...split(/\s*z\s*/i); 

or you can just bind:

 ...split(/z/i).map(function (val) { return val.trim(); }); 
+3
source

Here you can use the regular expression /\s*z\s*/i to separate:

 var str = "M50 0 L0 100 L100 100 L50 0 z M0 0 L100 0 L50 100 L0 0 Z"; var arr4String = str.split(/\s*z\s*/i); document.body.innerHTML = "<pre>" + JSON.stringify(arr4String,0,4) + "</pre>"; 

The regular expression /\s*z\s*/i will match zero or more spaces ( \s* ) before and after z (case-insensitive searches are performed using the /i modifier).

+1
source

You're close, but you want to use a regex instead of a string, which you can use using a slash instead of quotation marks ( /z|Z/ ).

However, just using this will not give you what you want. You really want a regular expression that removes the surrounding spaces around your z characters. Also, suppose if you pass a line containing "L100z200" , you do not want this to be split in the middle. To accomplish this, you can use \b to make sure that a word boundary exists. Here you are:

 var str = "M50 0 L0 100 L100 100 L50 0 z M0 0 L100 0 L50 100 L0 0 Z"; var arr4String = str.split(/\b\s*z\s*\b/i); console.log(arr4String); // Exactly: // ["M50 0 L0 100 L100 100 L50 0", "M0 0 L100 0 L50 100 L0 0", ""] 
0
source
 var arr4String = str.replace('z','Z').split('Z'); 
0
source

For completeness only (may be faster than / z / i):

 var arr4String = str.split(/[zZ]/); 
0
source

All Articles