Is there a way to combine these two .replace statements into one?
.replace(/(\[((size=)(1|2|3|4|5|6))\])/gi, '<font size="$4">')
.replace(/(\[((\/)(size))\])/gi, '</font>')
I am not sure if there is a way.
Is there a way to combine these two .replace statements into one?
.replace(/(\[((size=)(1|2|3|4|5|6))\])/gi, '<font size="$4">')
.replace(/(\[((\/)(size))\])/gi, '</font>')
I am not sure if there is a way.
You cannot use just 1 regex for it since you have 2 different replacement strings. However, you can capture these tags with 1 regex, and then chain another replace method to tranform "bad" <font> tag to the closing one.
I presume that there will be no attributes with empty values.
var re = /\[\/?size(?:=([1-6]))?\]/gi;
var str = '[size=6][/size]';
var subst = '<font size="$1">';
var result = str.replace(re, subst).replace(/<font size="">/, "</font>");
// Now, just display
document.getElementById("res").value = result;
<input id="res"/>
/\[\/?size(?:=([1-6]))?\]/gi(\/?) make sense if you use a replacement function to evaluate whether it is open tag or close tag to replace accordingly, rather than this hack-ish solution where you replace the failed open tag replacement with close tag.Try this single regex:
var re = /\[(size)=(\d{1,6})\]([^\[]+)\[\/size\]/gi;
var str = '[size=2]dd\n[/size]';
var subst = '<font size="$2">$3</font>';
var result = str.replace(re, subst);
regex expain:
\[(size)= //capture [, size and =
(\d{1,6})\] //capture size number and ]
([^\[]+) //capture between [size=3] and [/size]
\[\/size\] //capture [/size]
var re = /\[(size)=(\d{1,6})\]([^\[]+)\[\/size\]/gi;
var str = '[size=2]dd\n[/size]';
var subst = '<font size="$2">$3</font>';
var result = str.replace(re, subst);
$("#b").val(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" style="width:100%" id="b" />