javacript replace 正则取字符串中的值并替换【推荐】
replace()方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
问题:
在使用ueditor富文本编辑器,给字体颜色时,发现getCent后的内容颜色为rgb
如
而前端需求rgb的读取不了,因此要转成16进制的颜色。找了uedtitor编辑器一圈,没找到方法。
因此。我想到的解决方法是,在提交保存之前,把富文本里的内容找出rgb颜色并替换成16进制颜色。
解决的js如下
functiondoSubmit(){ varcontent=UE.getEditor('messageTemplate').getContent(); content=content.replace(/rgba?\(\s?\d+\s?,\s?\d+\s?,\s?\d+\s?\)/g,function(){ returnfixColor('color',arguments[0]); }) ....... } //rgb颜色转16进制 functionfixColor(name,value){ if(/color/i.test(name)&&/rgba?/.test(value)){ console.log(value); vararray=value.split(","); if(array.length>3){ return""; } value="#"; for(vari=0,color;color=array[i++];){ color=parseInt(color.replace(/[^\d]/gi,''),10).toString(16); value+=color.length==1?"0"+color:color; } value=value.toUpperCase(); } returnvalue; }
js正则replace还是好用的哈。
functiontest(){ varstr="";//目标替换成 str=str.replace(/color_tag=\"(#.{6})\"/g,function(){ return"="+arguments[1]; }) console.log(str); }
总结
以上所述是小编给大家介绍的javacriptreplace正则取字符串中的值并替换,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!