Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transform '#ff00fffirstword#445533secondword#008877thirdword' to html tag format

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.

like image 888
Rex Smith Avatar asked Jun 02 '13 14:06

Rex Smith


2 Answers

Description

You could use this regex

Regex: ([#][0-9a-f]{6})(.*?)(?=[#]|$) Replace with <font color='\1'>\2</font>

enter image description here

Javascript Code Example:

<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>
like image 177
Ro Yo Mi Avatar answered Sep 30 '22 21:09

Ro Yo Mi


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:

Regular expression image

like image 23
Jerry Avatar answered Sep 30 '22 20:09

Jerry