替换字符串值

时间:2015-09-03 08:05:10

标签: javascript jquery regex string replace

我在随机位置有一个包含各种十六进制值的字符串。

是否可以将所有十六进制值替换为单个值#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()不起作用,因为字符串中的十六进制值不同。

4 个答案:

答案 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替换字符串中的所有十六进制值。

&#13;
&#13;
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;
&#13;
&#13;

正则表达式解释

  1. #:匹配# literal
  2. [a-f0-9]:匹配从af09
  3. 的任何范围
  4. {6}:匹配上一个字符类6
  5. gi:全球和不敏感的匹配。
  6. 正则表达式可视化

    Regex Visualization

答案 2 :(得分:3)

replace() 与正则表达式用作/#[\da-f]{6}/,同时添加标记ig以忽略大小写和全局匹配

&#13;
&#13;
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;
&#13;
&#13;

说明:

#[\da-f]{6}
  1. #匹配字符#
  2. \d用于匹配任何数字
  3. a-f用于匹配字母a,b,c,d,e或f,因为十六进制值仅包含这些字母
  4. {6}正好6次
  5. Regular expression visualization

    Debuggex Demo

    Regex demo

答案 3 :(得分:2)

是的,使用带有/#[A-F0-9]{6}/gi功能的正则表达式replace()

&#13;
&#13;
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;
&#13;
&#13;

这将匹配任何十六进制值并替换它。

<强>解释

  • #字面匹配字符#
  • A-F A和F之间范围内的单个字符。
  • 0-9 0到9之间范围内的单个字符。
  • 量词: {6}恰好6次。
  • g修饰符:全局。所有比赛(首场比赛都没有回复)。