Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing string value

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.

like image 321
Becky Avatar asked Aug 03 '26 00:08

Becky


2 Answers

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>
like image 83
Arun P Johny Avatar answered Aug 04 '26 13:08

Arun P Johny


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}
  1. # matches the character #
  2. \d for matching any digit
  3. a-f for matching letters a,b,c,d,e or f, since hex value contains only these alphabets
  4. {6} Exactly 6 times

Regular expression visualization

Debuggex Demo

Regex demo

like image 37
Pranav C Balan Avatar answered Aug 04 '26 15:08

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!