0

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.

2
  • please provide your input output sample... Commented May 10, 2015 at 18:18
  • Why is this necessary? Commented May 10, 2015 at 18:49

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

The capturing groups are quite excessive here. Should be possible to reduce to just /\[\/?size(?:=([1-6]))?\]/gi
@nhahtdh: Yes, possible, we just never know what OP really wants to do with them later. Thus, I tend to keep to original ones.
Actually, capturing the backslash (\/?) 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.
1

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

1 Comment

I like the way your answer is written. The idea of just using 1 regex to match opening and close tags is good, but what if they are not in the same input string? Perhaps, that is the main problem here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.