我在随机位置有一个包含各种十六进制值的字符串。
是否可以将所有十六进制值替换为单个值#FF0000
?
var info_str = 'The avocado, also known as butter pear or alligator pear, is a fruit that is widely "acknowledged to #E5E5E5 have properties" that reduce cholesterol levels... also #00FF00 ...';
我需要将所有十六进制值#xxxxxx
替换为#FF0000
。我怎么能这样做?
replace()
不起作用,因为字符串中的十六进制值不同。
答案 0 :(得分:4)
您可以使用像
这样的简单正则表达式
var info_str = 'The avocado, also known as butter pear or alligator pear, is a fruit that is widely "acknowledged to #E5E5E5 had (property" that reduce cholesterol levels... also #00FF00 ...';
var str = info_str.replace(/#[\da-z]+/ig, '#FF0000');
snippet.log(str)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
答案 1 :(得分:3)
您可以使用regex
替换字符串中的所有十六进制值。
var info_str = 'The avocado, also known as butter pear or alligator pear, is a fruit that is widely "acknowledged to #E5E5E5 have properties" that reduce cholesterol levels... also #00FF00 ...';
var replaced = info_str.replace(/#[a-f0-9]{6}/gi, '#FF0000');
document.write(replaced);
&#13;
正则表达式解释
答案 2 :(得分:3)
将 replace()
与正则表达式用作/#[\da-f]{6}/
,同时添加标记ig
以忽略大小写和全局匹配
var info_str = 'The avocado, also known as butter pear or alligator pear, is a fruit that is widely "acknowledged to #FFF001 have properties" that reduce cholesterol levels... also #00FF00 ...';
document.getElementById('myDiv').innerHTML = info_str.replace(/#[\da-f]{6}/ig, '#FF0000');
&#13;
<div id="myDiv"></div>
&#13;
说明:
#[\da-f]{6}
#
匹配字符#\d
用于匹配任何数字a-f
用于匹配字母a,b,c,d,e或f,因为十六进制值仅包含这些字母{6}
正好6次
答案 3 :(得分:2)
是的,使用带有/#[A-F0-9]{6}/gi
功能的正则表达式replace()
:
var info_str = 'The avocado, also known as butter pear or alligator pear, is a fruit that is widely "acknowledged to #E5E5E5 have properties" that reduce cholesterol levels... also #00FF00 ...';
var replaced = info_str.replace(/#[A-F0-9]{6}/gi, "#FF0000");
document.write("<b>"+replaced+"</b>");
&#13;
这将匹配任何十六进制值并替换它。
<强>解释强>
#
字面匹配字符#
。A-F
A和F之间范围内的单个字符。0-9
0到9之间范围内的单个字符。{6}
恰好6次。g
修饰符:全局。所有比赛(首场比赛都没有回复)。