替换短语中除破折号以外的所有破折号

replace all dashes but dash in phrase

本文关键字:破折号 替换 短语      更新时间:2023-09-26

我正在尝试用空格替换字符串中的所有破折号,除非破折号在短语 "not-replace" 中。所以整个字符串就像

var str = "change-these-dashes-but-not-replace-that";

所以我可能会以"更改这些破折号但不替换它"结束

但是我想出的并不是与我不想替换它的短语中的破折号不匹配。我该如何修改?

.match(/-(^not-replace)/gi);

这是另一种方法(如果使用,ES5 中的map可能会替换为 jQuery 中的$.map):

str.split('not-replace').map(function(s) {
    return s.replace(/-/g, ' ');
}).join('not-replace');  // "change these dashes but not-replace that"

甚至更短和(可能)更快的解决方案:

str.replace(/-|not-replace/g, function(s) { return s === '-' ? ' ' : s; });

最后一个将在所有浏览器中不断工作。

str.replace(/not-replace/, 'notXXXreplace').replace(/-/, ' ').replace(/notXXXreplace/, 'not-replace');

即首先通过将其更改为不包含破折号的不太可能的东西来保护not-replace。然后替换所有破折号,并放回不太可能的字符串所在的not-replace

现代Javascript现在支持后看断言,因此相应地编辑我的旧答案。

您可以将此正则表达式与嵌套的前瞻和后视一起使用:

repl = str.replace(/-(?!(?<='bnot-)replace'b)/g, ' ');
//=> change these dashes but not-replace that

正则表达式演示

正则表达式详细信息:

  • -:匹配-
  • (?!:开始负前瞻
    • (?<='bnot-) : 前面必须加上单词not-
    • replace'b : 匹配词replace
  • ):结束负面展望