Given are these strings:
var string1 = "Chapter_1";
var string2 = "Chapter_1a";
The desired result is:
"Chapter 1."
"Chapter 1. a)"
I could to this:
var string1new = string1.replace("_", " ").replace(/(d+)/, "$1.").replace(/.(w)$/, ". $1)"));
var string2new = string2.replace("_", " ").replace(/(d+)/, "$1.").replace(/.(w)$/, ". $1)"));
But I would prefer one single pattern/replacement. Something like:
var string1new = string1.replace(/(Chapter)_(d+)(w*)/, "$1 $2. $3)");
var string1new = string1.replace(/(Chapter)_(d+)(w*)/, "$1 $2. $3)");
Now how to conditionally insert $3)
depending on whether $3
is empty or not?
2
Answers
You can use a function with condition instead of result string:
You cannot do
$3) if $3 exists
or in other words: inline an optional replacement character ()
). Either you define the literal)
output – or you don’t. Instead create the necessary logic inside the String.prototype.replace callback function.