javascriptregexmatch

Match values in-between braces


I have a string like this: "hello %{name} good %{middle} bye".

I'm trying to find an effective way to extract out the values in-between the braces, so ideally I would end up with an array of ["name", "middle"].

Using match I can almost get there. The following returns: ['%{name}', '%{middle}']:

"hello %{name} good %{middle} bye".match(/%{([\w]+)}/g)

I'm not sure why it's including the %, {, and } characters in the return though.

How can I adjust my regular expression to only match name and middle?


Solution

  • You need to change your regex expression to capture the values inside the braces without the %, {, and } characters, you can modify it slightly.

    Existing: /%{([\w]+)}/g => /%\{(\w+)\}/g

    Refer the below examples:

    const str = "hello %{name} good %{middle} bye";
    const str1 = "hello %{aaa} good %{bbbb} bye";
    const str2 = "hello %{xyz} %{gtr} %{pqr} bye";
    
    const matches = str.match(/%\{(\w+)\}/g);
    const matches1 = str1.match(/%\{(\w+)\}/g);
    const matches2 = str2.match(/%\{(\w+)\}/g);
    
    const values = matches.map(match => match.slice(2, -1));
    const values1 = matches1.map(match => match.slice(2, -1));
    const values2 = matches2.map(match => match.slice(2, -1));
    
    console.log(JSON.stringify(values));
    console.log(JSON.stringify(values1));
    console.log(JSON.stringify(values2));

    Also, this can be achieved via non regex-based approach as well:

    const str = "hello %{name} %{world} %{middle} bye";
    const str1 = "hello %{aaa} %{bye} %{bbbb} bye";
    const str2 = "hello %{xyz} %{gtr} %{pqr} bye";
    const startDelimiter = "%{";
    const endDelimiter = "}";
    
    function extractValues(input, startDelimiter, endDelimiter) {
        const values = [];
        let startIndex = 0;
    
        while ((startIndex = input.indexOf(startDelimiter, startIndex)) !== -1) {
            startIndex += startDelimiter.length;
            const endIndex = input.indexOf(endDelimiter, startIndex);
            if (endIndex === -1) {
                break; 
            }
            const value = input.substring(startIndex, endIndex);
            values.push(value);
            startIndex = endIndex + endDelimiter.length;
        }
    
        return values;
    }
    
    const result = extractValues(str, startDelimiter, endDelimiter);
    const result1 = extractValues(str1, startDelimiter, endDelimiter);
    const result2 = extractValues(str2, startDelimiter, endDelimiter);
    
    
    console.log(JSON.stringify(result));
    console.log(JSON.stringify(result1)); 
    console.log(JSON.stringify(result2));