Can I transform string #ff00fffirstword#445533secondword#008877thirdword
to
<font color='#ff00ff'>firstword</font><font color='#445533'>secondword</font><font color='#008877'>thirdword</font>
Using regexp in javascript or actionscript3 program?
I tried the code below, but it's not perfect (actionscript3 code):
var pat:RegExp = /(#\w{6})([^#]+)/g;
var html:String = t.replace(pat, "<font color=\'$1\'>$2</font>");
trace(html); // output :<font color='#ff00ff'>firstword</font><font color='#445533'>secondword</font><font color='#008877'>thirdword</font>
If there one more #
in that string, the output would not be like I want it to be. I don't know how to write a stronger regexp to achieve this.
You could use this regex
Regex: ([#][0-9a-f]{6})(.*?)(?=[#]|$)
Replace with <font color='\1'>\2</font>
<script type="text/javascript">
var re = /([#][0-9a-f]{6})(.*?)(?=[#]|$)/;
var sourcestring = "#ff00fffirstword#445533secondword#008877thirdword";
var replacementpattern = "<font color='\1'>\2</font>";
var result = sourcestring.replace(re, replacementpattern);
alert("result = " + result);
</script>
$sourcestring after replacement:
<font color='#ff00ff'>firstword</font><font color='#445533'>secondword</font><font color='#008877'>thirdword</font>
Try using an or
(|
) operator and a lookahead for the end of line:
var pat:RegExp = /(#[0-9a-f]{6})([^#]+?)(?=#|$)/gi;
var html:String = t.replace(pat, "<font color=\'$1\'>$2</font>");
trace(html);
I would also personally use [0-9a-f]
instead of \w
here just in case. The lookahead (?=#|$)
ensures that it's the end of line or another hash. I also inserted the i
flag just in case as well.
Since you also have stray hashes, you can use this one:
var pat:RegExp = /(#[0-9a-f]{6})(.+?)(?=#[0-9a-f]{6}|$)/gi;
var html:String = t.replace(pat, "<font color=\'$1\'>$2</font>");
trace(html);
See the output here.
And the debuggex:
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