如何使用正则表达式javascript将大写更改为小写

Joh*_*ith 6 javascript regex

它可以是任何字符串,它应仅匹配大写部分并更改为小写,例如:

"It's around August AND THEN I get an email"

成为

"It's around August and then I get an email"

你可以看到这个词It's,August并且I应该被忽略

Sam*_*Sam 16

使用/\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
Run Code Online (Sandbox Code Playgroud)

此外,随意使用更复杂的表达.这个将查找长度为1+的大写单词,其中"I"作为例外(我也做了一个查看不同的句子的第一个单词,但这更复杂,并且在回调函数中需要更新逻辑,因为你仍然想要首字母大写):

\b(?!I\b)[A-Z]+\b
Run Code Online (Sandbox Code Playgroud)

  • 正则表达式引擎本身是否可以完成从大写到小写的替换? (4认同)

chr*_*con 5

没有正则表达式的解决方案:

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(' '));
Run Code Online (Sandbox Code Playgroud)