skip to Main Content

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


  1. You can use a function with condition instead of result string:

    const formatString = str =>
      str.replace(
        /(Chapter)_(d+)(w*)/,
        (_, headerName, point, subpoint) =>
          `${headerName} ${point}.${subpoint ? ` ${subpoint})` : ''}`
    );
    var string1new = formatString(string1);
    var string2new = formatString(string2);
    
    Login or Signup to reply.
  2. 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.

    const chapterify = (string) => {
      return string.replace(/(^[^_]+)_(d+)(w*$)/, (_, p1, p2, p3) => {
        return `${p1} ${p2}. ${p3 ? p3+")" : ""}`.trim()
      })
    };
    
    console.log( chapterify("Chapter_1") )
    console.log( chapterify("Chapter_1a") )
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search