正则表达式从javascript中的字符串中查找值

时间:2017-04-05 09:33:53

标签: javascript jquery regex

我有像这样的json

{
  "foregroundDark": "##FF1F6D",
  "foregroundLight": "##F4FF80",
  "background": "##3029FF",
  "background2": "#FFFFFF",
  "barFontColors": ".cmtyx_color_1 { background-color:#FFBF36 !important; }.cmtyx_border_color_1 { border-color: #FFBF36 !important; }.cmtyx_text_color_1 { color: #FFBF36 !important; }.cmtyx_color_2 { background-color:#40EFFF !important; }.cmtyx_border_color_2 { border-color: #40EFFF !important; } .cmtyx_text_color_2 { color: #40EFFF !important; } .cmtyx_color_3 { background-color:#52FF42 !important; }.cmtyx_border_color_3 { border-color: #52FF42 !important; }.cmtyx_text_color_3 { color: #52FF42 !important; }.cmtyx_color_4 { background-color:#3DAEFF !important; }.cmtyx_border_color_4 { border-color: #3DAEFF !important; }.cmtyx_text_color_4 { color: #3DAEFF !important; }"
}

从这个json你可以找到一个键barFontColors。我需要所有这些类的颜色值.cmtyx_text_color_1.cmtyx_text_color_2.cmtyx_text_color_3.cmtyx_text_color_4。只有没有!important的值。提前谢谢。

1 个答案:

答案 0 :(得分:0)

要从该未经调整的字符串中获取元素,请将该字符串转换为可以解析为javascript对象的字符串。

完成此操作后,您只需从对象中访问它的元素即可。



var myObj = {
  "foregroundDark": "##FF1F6D",
  "foregroundLight": "##F4FF80",
  "background": "##3029FF",
  "background2": "#FFFFFF",
  "barFontColors": ".cmtyx_color_1 { background-color:#FFBF36 !important; }.cmtyx_border_color_1 { border-color: #FFBF36 !important; }.cmtyx_text_color_1 { color: #FFBF36 !important; }.cmtyx_color_2 { background-color:#40EFFF !important; }.cmtyx_border_color_2 { border-color: #40EFFF !important; } .cmtyx_text_color_2 { color: #40EFFF !important; } .cmtyx_color_3 { background-color:#52FF42 !important; }.cmtyx_border_color_3 { border-color: #52FF42 !important; }.cmtyx_text_color_3 { color: #52FF42 }.cmtyx_color_4 { background-color:#3DAEFF !important; }.cmtyx_border_color_4 { border-color: #3DAEFF !important; }.cmtyx_text_color_4 { color: #3DAEFF !important; }"
};


var tmpBarFontColors = '{'+ myObj.barFontColors.replace(/-/g,'_') +'}';
tmpBarFontColors = tmpBarFontColors.replace(/\.(\w+)\s*\{\s*(\w+)\s*:\s*([#\w]+)\s*([!\w]+)?[^}]*\}/g, '"$1":{"$2":"$3","flag":"$4"}');
tmpBarFontColors = tmpBarFontColors.replace(/\}\s*"/g,'}, "');

myObj.barFontColors = JSON.parse( tmpBarFontColors );

//console.log(tmpBarFontColors );
console.log("cmtyx color 1 is " + myObj.barFontColors.cmtyx_color_1.background_color);
console.log(myObj.barFontColors);