Here's a simple way to accomplish this task using the pattern \[(\d+?)\](.+)
:
- The
(…)
is a capture group, indicating that whatever matches within the brackets will be saved as a token.
\d
represents a single digit.
\d+
means one or more digits in a row.
\d+?
signifies one or more digits, but matching the fewest possible before moving on.
.+
matches any character at least once.
In regular expressions, [
and ]
have special meanings, so if you want to include them literally, you must escape them like so: \[
and \]
.
The double backslashes \\
are used in JavaScript as an oddity when defining a regex from a string rather than using the /literal/
notation. Both methods achieve the same result.
There are numerous resources available for learning regex patterns, and http://regex101.com is an excellent platform for testing and experimenting with different patterns.
var input = "[4]Motherboard, [25]RAM";
var pattern = '\\[(\\d+?)\\](.+)';
var result = input.split(',').map(function (item) {
var matches = item.match(new RegExp(pattern));
return {id: matches[1], val: matches[2]};
});
console.log(result)