如何使用正则表达式 javascript 将大写更改为小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32256906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to change uppercase to lowercase with regex javascript
提问by John Smith
It could be any string, it should match only the UPPERCASE part and change to lowercase, for example:
它可以是任何字符串,它应该只匹配大写部分并更改为小写,例如:
"It's around August AND THEN I get an email"
"It's around August AND THEN I get an email"
become
变得
"It's around August and then I get an email"
"It's around August and then I get an email"
as you can see the word It's
, August
and I
should be ignored
你可以看到这个词It's
,August
并且I
应该被忽略
回答by Sam
Use /\b[A-Z]{2,}\b/g
to match all-caps words and then .replace()
with a callback that lowercases matches.
使用/\b[A-Z]{2,}\b/g
以匹配所有大写的单词,然后.replace()
用一个回调小写字母匹配。
var string = "It's around August AND THEN I get an email",
regex = /\b[A-Z]{2,}\b/g;
var modified = string.replace(regex, function(match) {
return match.toLowerCase();
});
console.log(modified);
// It's around August and then I get an email
Also, feel free to use a more complicated expression. This one will look for capitalized words with 1+ length with "I" as the exception (I also made one that looked at the first word of a sentence different, but that was more complicated and requires updated logic in the callback function since you still want the first letter capitalized):
另外,请随意使用更复杂的表达式。这个将查找长度为 1+ 的大写单词,“I”作为例外(我还制作了一个查看句子的第一个单词的不同单词,但这更复杂,并且需要在回调函数中更新逻辑,因为您仍然希望第一个字母大写):
\b(?!I\b)[A-Z]+\b
回答by baao
A solution without regex:
没有正则表达式的解决方案:
function isUpperCase(str) {
return str === str.toUpperCase();
}
var str = "It's around August AND THEN I get an email";
var matched = str.split(' ').map(function(val){
if (isUpperCase(val) && val.length>1) {
return val.toLowerCase();
}
return val;
});
console.log(matched.join(' '));