Regx 从字符串中提取模板标签 {{..}}

Mar*_*ebb 0 javascript regex

我需要从字符串中提取波浪形括号模板标签。例如:

var str="Hello {{user}}, your reference is {{ref}}"
Run Code Online (Sandbox Code Playgroud)

我想将 {{..}} 之间的标签提取到一个数组中。例如:

["user","ref"]
Run Code Online (Sandbox Code Playgroud)

我该怎么做,例如使用 Regx - 我需要忽略括号内的任何空格,例如 {{ user}} 需要返回“user”

Ben*_*Ben 5

你可以这样做:

var found = [],          // an array to collect the strings that are found
    rxp = /{{([^}]+)}}/g,
    str = "Hello {{user}}, your reference is {{ref}} - testing {one} braces. Testing {{uncomplete} braces.",
    curMatch;

while( curMatch = rxp.exec( str ) ) {
    found.push( curMatch[1] );
}

console.log( found );    // ["user", "ref"]
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。