我的字符串是:
'{ color : rgb(0,0,0);background-color : rgb(255, 255, 255);}'
我想匹配颜色和背景。
我的正则表达式是
a = new RegExp(prop + '[^;]+?\\;','g');
哪里
prop = `color` or `background-color`
背景匹配良好,但颜色两者都匹配。我试过了
a =new RegExp('[^d-]'+prop + '[^;]+?\\;','g');
它匹配 ;background-color : rgb(255, 255, 255);
但我只想要 background-color : rgb(255, 255, 255);
.
1) 我怎样才能得到它?
2)如果我想从字符串中删除background-color
,那么正则表达式是什么?
最佳答案
您可以首先使用以下正则表达式匹配所有属性:
/([\w-]+)\s*:\s*(.+?)[;}]/g
使用此输入:
var css = '{\
color: rgb(0,0,0);\
background-color: rgb(255, 255, 255);\
font-size: 2em;\
margin: 0;\
padding: 4px;\
font-style: italic;\
text-align: center;\
}'
它给出了这个输出:
var output = {}
s.replace(/([\w-]+)\s*:\s*(.+?)[;}]/g, function(_, k, v) {
output[k] = isNaN(v) ? v : +v // cast number if necessary
})
console.log(output)
/*^ { color: 'rgb(0,0,0)',
'background-color': 'rgb(255, 255, 255)',
'font-size': '2em',
margin: 0,
padding: '4px',
'font-style': 'italic',
'text-align': 'center' }
*/
然后您就可以动态访问您想要的 key :
var prop = 'color'
output[prop] //=> rgb(0,0,0)
关于javascript - 仅当字符串不以某些字符开头时才获取字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25673926/