0

我需要从字符串中提取花括号括起来的模板标签。例如:

var str="Hello {{user}}, your reference is {{ref}}"

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

["user","ref"]

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

4

1 回答 1

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"]

希望这可以帮助。

于 2020-03-16T21:55:58.083 回答