skip to Main Content

For example, there is a line:

const string = "a {{bcd}} e {{f}}"

The result will be an array like this:

const result = ["a", "{{bcd}}", "e", "{{f}}"];

I tried the following code, but the regex result was sent to the array.

let string = "a {{bcd}} e {{f}}"

string = string.replace(/s+/g, "");
const reg = /({{(.*?)}})/g
const a = string.split(reg);
console.log(a);

It turns out that it still saves the regex, but this is not necessary.

3

Answers


  1. To achieve the desired result, you can use a combination of regular expressions and the match method. Here’s a code example that splits the input string into an array while keeping the "((…))" parts intact:

    const inputString = "a ((bcd)) e ((f))";
    const regex = /((([^)]+)))/g;
    
    const result = inputString.split(regex).filter(Boolean);
    
    console.log(result);
    

    In this code:

    1. We define the input string inputString as "a ((bcd)) e ((f))".
    2. We define a regular expression regex that matches everything between "((…))" while excluding the parentheses themselves.
    3. We use the split method to split the input string using this regular expression. This will result in an array where the "((…))" parts are separated.
    4. We use filter(Boolean) to remove any empty strings from the resulting array.
    5. Finally, we print the result array, which should contain the desired output: ["a", "((bcd))", "e", "((f))"].

    This code should give you the expected result.

    Login or Signup to reply.
  2. You can use String::matchAll() to iterate all matches in a string and collect the capture groups:

    let string = " a {{bcd}} e {{f}}"
    
    const reg = /s*(.*?)s*({{.*?}})/g;
    const result = []
    for(const m of string.matchAll(reg)){
      result.push(...m.slice(1));
    }
    
    console.log(result);

    An one-liner:

    console.log( [..."a {{bcd}} e {{f}}".matchAll(/s*(.*?)s*({{.*?}})/g)].flatMap(m => m.slice(1)) );
    Login or Signup to reply.
  3. Explanation
    You could define the multiple combination of regex to match either "((…))" or any other character to capture all the possible substrings.

    After you get all the possible substrings in list, filter those empty using filter

    Code

    // Method 1: Regex by (()) after removing spaces
    string = "a ((bcd)) e ((f))"
    string = string.replace(/s+/g, "");
    reg = /((([^)]+)))/g
    a = string.split(reg).filter(Boolean);  
    console.log(a)
    
    // Method 2: Regex by (( )) with spaces
    string = "a ((bcd)) e ((f))"
    reg = /((([^)]*)))|s+/g
    a = string.split(reg).filter(Boolean);
    console.log(a)
    
    // Method 3: Regex by Spaces
    string = "a ((bcd)) e ((f))"
    /* string = string.replace(/s+/g, ""); */
    reg = /s+/g
    a = string.split(reg);
    console.log(a)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search