【问题标题】:Dynamic RegExp with case preservation in JavaScript在 JavaScript 中保留大小写的动态正则表达式
【发布时间】:2015-10-08 09:26:55
【问题描述】:

我想做的是编写一个函数来替换给定句子中的单个单词。其中一项要求是,被替换的单词的大小写将与原始单词一样保留。

我写了以下函数:

function replace(str, before, after) {
  var re = new RegExp('(\\.*)?(' + before + ')(\\.*)?', 'i');
  return str.replace(re, after);
}


// DEBUG
console.log('----- DEBUG START -----');

var tasks = [
  replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"),
  replace("Let us go to the store", "store", "mall"),
  replace("He is Sleeping on the couch", "Sleeping", "sitting"),
  replace("This has a spellngi error", "spellngi", "spelling"),
  replace("His name is Tom", "Tom", "john"),
  replace("Let us get back to more Coding", "Coding", "bonfires"),
];

for (var i = 0; i < tasks.length; i++) {
  console.log('Result #' + i + ': ' + tasks[i]);
}

console.log('----- DEBUG END -----');

除了after 单词的大小写与before 单词的大小写不同之外,一切正常。

信息:

我使用数组(使用split()splice()indexOf())解决了同样的问题,并且只用非动态RegExp() 替换了before 元素,并保留了案例。这就是为什么我不太明白为什么我的其他解决方案不起作用的原因。

【问题讨论】:

    标签: javascript regex replace


    【解决方案1】:

    您正在用另一个字符串替换一个字符串。 JS 不会神奇地将原始单词的大写应用于替换单词,因为这可能会导致潜在的不良行为。如果您必须保留字符的大小写,则需要竭尽全力。

    如果只关心首字母的大小写,可以在replace函数中进行如下操作:

    function replace(str, before, after) {
      var b0 = before[0];
      after = after.replace(/^(.)/, function(a0){
        return b0.toUpperCase() === b0 ? a0.toUpperCase() : a0.toLowerCase();
      });
      var re = new RegExp('(\\.*)?(' + before + ')(\\.*)?', 'i');
      return str.replace(re, after);
    }
    
    // DEBUG
    document.write('----- DEBUG START -----<br>');
    
    var tasks = [
      replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"),
      replace("Let us go to the store", "store", "mall"),
      replace("He is Sleeping on the couch", "Sleeping", "sitting"),
      replace("This has a spellngi error", "spellngi", "spelling"),
      replace("His name is Tom", "Tom", "john"),
      replace("Let us get back to more Coding", "Coding", "bonfires"),
    ];
    
      for (var i = 0; i < tasks.length; i++) {
      document.write('Result #' + i + ': ' + tasks[i]+'<br>');
    }
    
    document.write('----- DEBUG END -----');

    【讨论】:

    • 谢谢 - 我没想到。
    猜你喜欢
    • 2014-11-28
    • 2014-05-12
    • 1970-01-01
    • 2017-12-30
    • 2011-04-25
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    相关资源
    最近更新 更多