Michael Jones
Michael Jones

Reputation: 2282

Complex BBCode To HTML Regex With .replace

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.

Upvotes: 0

Views: 111

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

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"/>

Upvotes: 1

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

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" />

Demo

Upvotes: 1

Related Questions