Skip to content
Advertisement

JS Regex named groups with replace()

In JS, I’m trying to build an object from the below code. However I’m stuck at getting regex named groups with the below replace function.

var formatters = {
    'p': 'padding',
    'm': 'margin',
    'd': 'border',  // Had to use letter "d", Becuase "b" means "bottom".
    't': '-top',
    'b': '-bottom',
    'l': '-left',
    'r': '-right'
}

var str = 'p:[p], pt:[p][t], pb:[p][b], rounded-tr:[d][t][r]-radius'

var match = str.replace(/:(?<selection>.*?)(:?,)/g, (m) => formatters[m])

// var expectedOutput = {'p':'padding', 'pt':'padding-top', 'pb':'padding-bottom', 'rounded-tr': 'border-top-right-radius'}

NOTE: What I’m trying to do is, Select characters from str variable from “:” to “,” and replace it with formatters values. Then make the string an object.

Advertisement

Answer

Regex Demo

[([a-z])]

var formatters = {
  'p': 'padding',
  'm': 'margin',
  'd': 'border', // Had to use letter "d", Becuase "b" means "bottom".
  't': '-top',
  'b': '-bottom',
  'l': '-left',
  'r': '-right'
}

var str = 'p:[p], pt:[p][t], pb:[p][b], rounded-tr:[d][t][r]-radius'

var match = str.replace(/[([a-z])]/g, (m, p1) => formatters[p1])

console.log(match)

var expectedOutput = Object.fromEntries(match.split(', ').map(s => s.split(':')))

console.log(expectedOutput)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement