skip to Main Content

I’m trying to reformat a list. The function matches certain areas of the original string and reformat those into a "properties" section which has to have the string "—" before and after it. ex,

input:

| name = Malik
| age = 55
| hair = brown

Output:

---
name: malik
age: 55
hair: brown
---

I managed to add "—" before all the matches, but how would I go about only adding the second string after the last match of the replace function?
I tried many approaches but failed horribly. the closest I got was when it added "—" after the first match.

2

Answers


  1. Chosen as BEST ANSWER

    As expected, after struggling with this issue for literal hours, giving up, posting this question and letting go, I finally got an idea on how to do this and it worked! In case anyone might run into a similar situation what I ended up doing is:

    const totalMatches = string.match(regexp).length; // finds the total amount of matches
    let matchIndex = 0; // creates an empty index
    string.replace(regexp, function replacer(match, name, value) {
      matchIndex += 1; //adds one each cycle to the index
      let result = `${name}: ${value}n`;
      if (matchIndex === totalMatches) { //adds the string only when it is the last cycle.
        result += "---n";
      }
      return result
    })
    

  2. Do this as two levels of replacement. Use one regexp to match the entire sequence of lines, so you can add --- around it. Then in the replacement function for that, you can use another replacement to reformat each line.

    const input = `| name = Malik
    | age = 55
    | hair = brown
    
    | name = James
    | age = 24
    | hair = blond
    `;
    
    const output = input.replace(/(?:^|.*n)+/gm,
      (match) => 
        '---n' +
        match.replace(/^|s*(w+)s*=s*(.*)/gm, '$1: $2') +
        '---n');
    
    console.log(output);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search