代码之家  ›  专栏  ›  技术社区  ›  altendky

JavaScript正则表达式-替换时强制使用大小写

  •  1
  • altendky  · 技术社区  · 15 年前

    JavaScript正则表达式标准在执行搜索/替换时是否支持强制case?

    我通常知道\u等选项用于强制正则表达式替换部分中捕获组的大小写。不过,我不知道如何在JavaScript正则表达式中实现这一点。 我无法访问JavaScript代码本身

    3 回复  |  直到 15 年前
        1
  •  1
  •   zen    15 年前

    如果我没弄错的话,我不会的。

    不能从正则表达式模式中计算javascript(将匹配项转换为大写)。

    我只知道str.replace()可以转换为大写。

        2
  •  1
  •   localshred    15 年前

    字符串匹配是使用正则表达式完成的。但是,字符串替换只关心要替换的主题字符串的哪一部分(由正则表达式匹配提供),它只根据您提供的内容直接替换字符串:

    var subject = "This is a subject string";
    
    // fails, case-sensitive match by default
    subject.replace(/this/, "That"); 
    
    // succeeds, case-insensitive expression using /i modifier, replaces the word "This" with the word "That"
    subject.replace(/this/i, "That"); 
    

    var subject = "This is a subject string";
    var matches = subject.match(/(subject) string/i);
    if (matches.length > 0)
    {
        // matches[0] is the entire match, or "subject string"
        // matches[1] is the first group match, or "subject"
        subject.replace(matches[1], matches[1].toUpperCase());
        // subject now reads "This is a SUBJECT string"
    }
    

    简言之,如果愿意,进行匹配可以处理大小写敏感问题。进行替换非常简单,只需告诉它使用哪个直接字符串进行替换即可。

        3
  •  0
  •   Asaph    15 年前

    /i 旗帜