JavaScript:输入字符串并将大写字母转换为小写字母,反之亦然
swapcase = function swapcase(str) {
return str.replace(/([a-z]+)|([A-Z]+)/g,
function(match, chr) {
return chr ? match.toUpperCase() : match.toLowerCase();
});
}
console.log(swapcase('AaBbc'))
最佳答案
`/(a-z)+|(A-Z)+/`
(a-z)+
- 匹配任意小写字符一次或多次。 (捕获组 1)|
- 与逻辑 OR 相同的交替(A-Z)+
- 匹配任何大写字符一次或多次。 (捕获组 2)
JS replace方法具有以下结构
str.replace(regexp|substr, newSubstr|function)
这里这个函数需要 parameters为 (match, group1,group2..., offset,string)
const swapcase = function swapcase(str) {
return str.replace(/([a-z]+)|([A-Z]+)/g, function(match, chr) {
return chr ? match.toUpperCase() : match.toLowerCase(); });
}
console.log(swapcase('AaBbc'))
因此,在您的代码中,chr
是第 1 组。它仅匹配小写字符。在您的返回中,您的交换案例基于 chr
关于javascript - 这个正则表达式如何实现从大写到小写的交换,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54613799/