javascript - 在 JavaScript 中保留大小写的动态正则表达式

标签 javascript regex replace

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

我写了下面的函数:

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())解决了同样的问题,并且只替换了 before 元素与一个非动态 RegExp() 并且大小写被保留。这就是为什么我不太明白为什么我的其他解决方案不起作用。

最佳答案

您正在用另一个字符串替换一个字符串。 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 -----');

关于javascript - 在 JavaScript 中保留大小写的动态正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31496472/

相关文章:

string - 用于替换较大子字符串中匹配子字符串的 Bash 脚本

Python:替换字符串中的十进制数

javascript - 解析 JSON json_encoded 数据库结果

javascript - 从 JS 调用 IE Js 调试器

javascript - 在 WP Rest API 中获取基于 WooCommerce 产品 URL 的featured_image

PHP 正则表达式解决方案 - 删除一些特殊字符并用文本替换一些

javascript - 带有图例和其他颜色的 Google Charts API 散点图

c# - 替换字符或序列列表中未包含的所有字符

java - 将特定行上的数字分配给变量

python - 比较、排除和从列表中弹出元素 (Python)