I've got a string with various hex values in random places.
Is it possible to replace all hex values to a single value #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 ...';
I need to replace all hex values #xxxxxx with #FF0000. How can I do that?
replace() does not work because the hex values in the string are different.
You can use a simple regex like
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>
Use replace() with regex as /#[\da-f]{6}/ , also add flags ig for ignoring case and global match
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');
<div id="myDiv"></div>
Explanation :
#[\da-f]{6}
# matches the character #\d for matching any digita-f for matching letters a,b,c,d,e or f, since hex value contains only these alphabets{6} Exactly 6 times 
Debuggex Demo
Regex demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With