代码:
strx = "exam/unwanted_tex/ple";
strx = strx.replace(/\/.+\//, '');
alert(strx); // Alerts "example"
2 个简单问题:
- 此代码会替换“/”和“/”内的所有内容?
- 使用“.*”而不是“.+”有什么区别
最佳答案
是
'*'
和'+'
称为量词。'*'
匹配其前面零次或多次的字符或组。从某种意义上说,这使得匹配成为可选的。'+'
匹配前面一次或多次的字符或组。在您的特定示例中,没有实际差异。然而,当在其他应用程序中使用时,这种区别非常重要。这是一个例子:
'*'
量词(匹配零次或多次)
// Match 'y' in Joey zero or more times
strx = "My name is Joe";
strx = strx.replace(/Joey*/, 'Jack');
alert(strx) // Alerts "My Name is Jack"
'+'
量词(匹配一次或多次)
// Match 'y' in Joey one or more times
strx = "My name is Joe";
strx = strx.replace(/Joey+/, 'Jack');
alert(strx) // Alerts "My Name is Joe"
关于javascript - 正则表达式通配符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7199125/