如何在Javascript中从字符串中获取占位符?
我有一个包含以下格式的一个或多个占位符的字符串:$([name]) [name]可以是任何单词(包含数字字符),并且区分大小写如何在Javascript中从字符串中获取占位符?,javascript,regex,Javascript,Regex,我有一个包含以下格式的一个或多个占位符的字符串:$([name]) [name]可以是任何单词(包含数字字符),并且区分大小写 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) l
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']
谢谢。用a和读一下这个
您可以在上看到更多信息,正如其他答案所提到的,最好的方法是将正则表达式与JavaScript
string.match()函数一起使用。我的正则表达式不是最好的(谁的),但这应该可以做到:
谢谢
你听说过正则表达式吗?标签有完全不同的含义。很少修改:使用regex=/\$\(\w+)/g
和arr=[];而(match=regex.exec(example1)){arr.push((match[1]);}
我们就到了。
function getPlaceholders(str)
{
var regex = /\$\((\w+)\)/g;
var result = [];
while (match = regex.exec(str))
{
result.push(match[1]);
}
return result;
}