Hello! The task is to split the string '156.75m ^ 2' into an array through a regular partition. My code

var reg = /(\d+)(\.)?(\d+)?(m)(\^)(2)/, str = '156.75m^2', mas = str.split(reg); 

Everything works well, but because the first and last element of the array is an empty string!

 ["", "156", ".", "75", "m", "^", "2", ""] 

Why is this happening and how to fix it? Thanks to all!

  • because in your case you need not split, but some kind of match - Grundy
  • With match, the first element is the entire spec that was transferred ["156.75m ^ 2", "156", ".", "75", "m", "^", "2", index: 0, input: "156.75 m ^ 2 "] this is also not suitable. - Slava
  • Array.from('156.75m^2'.match(/(\d+)(\.)?(\d+)?(m)(\^)(2)/)).slice(1) ? - user207618

2 answers 2

For example:

 var reg = /(\d+)(\.)?(\d+)?(m)(\^)(2)/, str = '156.75m^2', mas = reg.exec(str); console.dir(mas); 

When executing RegExp.exec (), the zero element is always the original string. If it is not needed, add mas = mas.slise (1);

    String#split() splits a string by a pattern, i.e. Substrings between matches are added to the resulting array, including empty lines at the beginning / end and between matches. In addition, when using exciting submasks, captured substrings are also added to the final array, which is sometimes necessary, but not in this case. Here you need to use String#match or RegExp#exec and delete the first element of the array if a match was found:

     var reg = /(\d+)(\.)?(\d+)?(m)(\^)(2)/; var str = '156.75m^2'; var mas = reg.exec(str); // Находим первое совпадение if (mas) { mas = mas.slice(1); // Удаляем первый элемент, полное совпадение } console.log(mas);