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

Can I convert the 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 actioncript3 program?

I tried the code below, but it is 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 is another # in this line, the result will not be what I want. I do not know how to write a strong regexp to achieve this.

+6
source share
2 answers

Try using the or ( | ) operator and look at the end of the 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. Seeing (?=#|$) Ensures that it is the end of a line or another hash. I also added the i flag just in case.

Since you also have wandering hashes, you can use this:

 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 debuggex:

Regular expression image

+5
source

Description

You can use this regex

Regex: ([#][0-9a-f]{6})(.*?)(?=[#]|$) Replace <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> 
+6
source

Source: https://habr.com/ru/post/946346/


All Articles