const rgx = /\D*(\d)(\d)+/g
Regex101
| Segment |
Description |
\D* |
Zero or more non-digits |
(\d) |
First capture group of a digit |
(\d)+ |
Second capture group of one or more digits |
g |
global flag |
.replace() with
"group[$1] - $1$2$2\n"
| Segment |
Description |
group[$1] |
Replace with literal: group[, then the first capture group of (\d), and then a literal: ] |
- |
Then a space, a literal hyphen -, and a space |
$1$2$2\n |
Next, the first capture group again: (\d), then the second capture group: (\d)+ twice, and finally a newline |
Example A
const str = `unit: 100 street: 200 city: 300`;
const rgx = /\D*(\d)(\d)+/g;
const res = str.replace(rgx, "group[$1] - $1$2$2\n");
console.log(res);
Note: The following comment was not considered in Example A:
It need not be numbers, could be any text."
The question should have this criteria added and an appropriate example:
'unit: 100 street: Main city: Springfield'
Because of this part: group[?], more than one method is needed. See Example B for a solution.
Example B
const str = 'unit: 100 street: Main city: Springfield';
const rgx = /\b(\w+:) ([\w]+)/g;
const res = str.replace(rgx, "$2")
.split(' ')
.map((s, i) =>
"group["+(i + 1)+"] - "+s).join('\n');
console.log(res);
/:\s(\d{3})/?