开发者

regular expressions and ascii color escapes

开发者 https://www.devze.com 2023-03-20 10:50 出处:网络
I have a script that outputs code with lots of ASCII escape开发者_开发知识库 sequences pertaining to color (for example, \\033[91m changes the color of the text to red when printed to a terminal). I\'

I have a script that outputs code with lots of ASCII escape开发者_开发知识库 sequences pertaining to color (for example, \033[91m changes the color of the text to red when printed to a terminal). I'd like to try to output this to HTML, so I tried this:

str = str.replace(new RegExp('\033[91m', 'g'),
                 '<span style="color:#ff0011">')
         /*.replace more such codes*/;

However, I get the following error:

SyntaxError: Invalid regular expression: /[91m/: Unterminated character class

How can I fix that?


You can put the [ inside a character class like this:

str = str.replace(new RegExp('\033[[]91m', 'g'),
             '<span style="color:#ff0011">');

http://jsfiddle.net/Wd5au/


Change it to '\033\\[91m'. I.e. you have to escape the '[' so that it doesn't think you are giving it a list of characters to match in that position.


var str = 'blahblah\033[91mblahblah';
str = str.replace(new RegExp('[\\033[91m]+', 'g'),
             '<span style="color:#ff0011">');

alert(str);

Example: http://jsfiddle.net/8bybx/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号