How to split a string in a regular expression into one S or E char followed by numbers in JavaScript?

I have a line like the following.

ids = 'S1486S1485E444' 

I want to split it into an array of parts separated by S or E, as shown below.

 ["S1486", "S1485", "E444"] 

This is what I came up with, but it also gives undefined and blank lines.

 ids.split(/(S+\d+)|(E+\d+)/) ["", "S1486", undefined, "", "S1485", undefined, "", undefined, "E444", ""] 
+4
source share
4 answers

Or just do a match:

 'S1486S1485E444'.match(/([SE]+\d*)/g) 
+3
source

You can use lookahead to separate at the border of a character, where S or E is the following character:

 var ids = 'S1486S1485E444'; var result = ids.split(/(?=S|E)/); // S1486,S1485,E444 

The reason for this is that while .split usually deletes the character in which it matches, it does not match the character itself, but the place where the next character is the one you want.

+3
source

The .split() argument is the delimiter by which you want to split the string. If this regular expression contains comparable groups (indicated by parentheses), then they are also included in the result.

One way will be similar to what you have, but then filter out all blank lines.

 ids.split(/([SE]\d+)/).filter(Boolean); // result: ["S1486", "S1485", "E444"] 

If your target browsers don't have a .filter in the Array prototype, you will have to implement this for yourself, sorry. Alternatively, just get every second value from the result:

 ids.split(/([SE]\d+)/) // result: ["", "S1486", "", "S1485", "", "E444", ""] 

From there, a simple for loop can get you the parts you need.

+1
source

If you use the .match() method, it will return an array containing all matches:

 ids.match(/(S\d+|E\d+)/g) // OR ids.match(/([SE]\d+)/g) 

Note that I changed the regex a bit and you need the g flag for .match() to return an array. If there are no matches, it returns null .

0
source

Source: https://habr.com/ru/post/1393873/


All Articles