Get value from key-value string
Solution 1:
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]
}
Solution 2:
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}