javascriptregex

JS Regex MatchAll with combination of Comma & Semicolon


I'm having a requirement of js regex should return the object from String.

String: 'A: 100 - 200, B B: Test & Test2, Tes3, C:, D: 11 22, E: E 444,55E'

Output:

{
'A': '100 - 200',
'B B': 'Test & Test2, Tes3',
'C': '',
'D': '11 22',
'E': 'E 444,55E'
}

I tried with following regex.

const regexp = /([^:]+): ?([^,]*),? ?/g;

But the output was not correct. Value for E is wrong.

{A: '100 - 200', B B: 'Test & Test2, Tes3', C: '', D: '11 22', E: 'E 444'} 
enter code here

Solution

  • Similar to other answers, in one functional expression:

    const input = 'A: 100 - 200, B: Test & Test2, Tes3, C: 40, D: 11 22, E: E 444,55E'
    
    const result = Object.fromEntries(Array.from(
        input.matchAll(/([^\s,:]+)\s*:\s*([^:]+)(?=,|$)/g), ([, ...pair]) => pair
    ));
    
    console.log(result);

    If speed is important, then use the traditional exec method:

    const input = 'A: 100 - 200, B: Test & Test2, Tes3, C: 40, D: 11 22, E: E 444,55E'
    
    let re = /([^\s,:]+)\s*:\s*([^:]+)(?=,|$)/g, match, result = {};
    while (match = re.exec(input)) result[match[1]] = match[2];
    
    console.log(result);