如何从Javascript中的字符串获取占位符?

时间:2012-06-27 08:41:06

标签: javascript regex

我有一个包含一个或多个占位符的字符串,格式如下: $( [name]

[name] 可以是任何字词(包含alfanumeric字符),区分大小写。

 Example1: 'The $(Quick) Brown fox jumps over the lazy dog'
 Example2: '$(the) $(Quick) Brown fox jumps over $(the) lazy dog'
 Example3: '$(the) $(Quick) Brown $(fox) jumps over $(the) lazy $(dog)'

javascript中检索所有占位符的最佳方式是什么,以便我们得到以下结果:

 Example1: ['Quick']
 Example2: ['the', 'Quick', 'the']
 Example3: ['the', 'Quick', 'fox', 'the', 'dog']

我还需要检索一个唯一的占位符列表,因此:

 Example1: ['Quick']
 Example2: ['the', 'Quick']
 Example3: ['the', 'Quick', 'fox', 'dog']

谢谢。

3 个答案:

答案 0 :(得分:2)

正如其他答案所提到的,您最好的方法是使用正则表达式和JavaScript string.match()函数。我的正则表达式不是最好的[],但这应该可以解决问题:

jsFiddle Demo

function getPlaceholders(str)
{
    var regex = /\$\((\w+)\)/g;
    var result = [];

    while (match = regex.exec(str))
    {
        result.push(match[1]);    
    }

    return result;
}

感谢freakish

答案 1 :(得分:0)

答案 2 :(得分:0)