-2
const str = 'scsi15';

const words = str.split(/[0-15]*$/);

Code output: Array ["scsi", ""],

However, this is the output I want: Array ["scsi", "15"]

Terry
  • 63,248
  • 15
  • 96
  • 118
  • do you have only one number? – Nina Scholz Mar 23 '20 at 07:27
  • 1
    `[0-15]` will be the same as `[015]` it's not "zero to fifteen" – VLAZ Mar 23 '20 at 07:29
  • Not quite. `[0-15]` means „Range 0 to 1 and the character 5”. That means, if it were `[0-25]` it would be equal to `[0125]` instead of `[025]`. – Ryuno-Ki Mar 23 '20 at 07:35
  • 1
    Does this answer your question? [Javascript and regex: split string and keep the separator](https://stackoverflow.com/questions/12001953/javascript-and-regex-split-string-and-keep-the-separator) – jonrsharpe Mar 23 '20 at 07:41
  • @Ryuno-Ki I was talking about *this* regex. The tange from zero to one includes zero *and* one only. – VLAZ Mar 23 '20 at 07:41

3 Answers3

0

You could match by non digits or digits.

const
    str = 'scsi15',
    words = str.match(/\D+|\d+/g);

console.log(words);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

One option would be to go via Regular Expression instead of String.prototype.split:

const str = 'scsi15';
const re = /([a-z]*)(\d*)/;
const words = re.exec(str);
// => ['scsi15', 'scsi', '15']

console.log(words)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Ryuno-Ki
  • 692
  • 1
  • 6
  • 8
0

You can destruct regex capturing groups if the order is always the same

const str = 'scsi15';
const re = /(\D*)(\d*)/;
const [_, word, num] = re.exec(str); // _, is first item. Could be just ,
console.log(word, num)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • `const [, word, num]` also works - you can skip the first identifier and not assign it. – VLAZ Mar 23 '20 at 07:41
  • 3
    @VLAZ I know, but I always explicit include it so it shows it is deliberately omitted and not a typo or somcething. – mplungjan Mar 23 '20 at 07:46