kaziutus
kaziutus

Reputation: 148

Get value from key-value string

I have a string:

const styleString = 'font-size: 24px; color: #f0f1f2; font-weight: 700;'

and I'd like to create a function which will looks like

const getStyleFromString = (styleString, styleName) => {
  // some logics
  return styleValue  
}
const fontSize = getStyleFromString(styleString, 'font-size') // returns 24px

Upvotes: 2

Views: 644

Answers (3)

A1exandr Belan
A1exandr Belan

Reputation: 4780

Just a quick code, for example:

const styleString = 'font-size: 24px; color: #f0f1f2; font-weight: 700;'

const getStyleFromString = (styleString, styleName) => {
  const [, value] = styleString
    .split(';')
    .map((style)=>style.split(':'))
    .find(([targetStyleName]) => 
      targetStyleName.trim().toLowerCase() === styleName.trim().toLowerCase()
    );
  
  return value.trim();
};

console.log(getStyleFromString(styleString, 'font-size'))
console.log(getStyleFromString(styleString, 'color'))
console.log(getStyleFromString(styleString, 'font-weight'))
.as-console-wrapper{min-height: 100%!important; top: 0}

Another way with JS object:

const styleString = 'font-size: 24px; color: #f0f1f2; font-weight: 700;'

const getStyleFromString = (styleString, styleName) => {
  const pairs = styleString
    .split(';')
    .map(pair => 
      pair.split(':').map(e => e.trim().toLowerCase()
    ));
  const obj = Object.fromEntries(pairs);
  
  return obj[styleName];
};

console.log(getStyleFromString(styleString, 'font-size'))
console.log(getStyleFromString(styleString, 'color'))
console.log(getStyleFromString(styleString, 'font-weight'))
.as-console-wrapper{min-height: 100%!important; top: 0}

Upvotes: 1

Mahdi Hamedi
Mahdi Hamedi

Reputation: 11

try this

function parseStyleString(styleString) {
  return styleString.split(';').map(item => item.trim()).filter(style => style).map(styleItem => {
    const [property, value] = styleItem.split(':');
    return {property: property.trim(), value: value.trim()};
  });
}

function getStyleFromString(styleString, styleName) {
  const parsedStyle = parseStringStyle(styleString);
  
  const findStyle = parsedStyle.find(({property}) => styleName === property);
  
  return findStyle?.value;
}

console.log(getStyleFromString('font-size: 24px; color: #f0f1f2; font-weight: 700;', 'font-size')); // return "24px"

Upvotes: 0

Daikozi
Daikozi

Reputation: 211

The idea is to remove : and ; from the string, split the string and filter the array generated to find the index of the property you are looking for and add 1 to that index

const getStyleFromString = (styleString, styleName) => {
  let styleArray = styleString.replace(/;|:/g, '').split(" ")
  let styleKey = styleArray.findIndex(element => element === styleName)
  return styleArray[styleKey + 1]
}

Upvotes: 1

Related Questions