首页 > 解决方案 > Javascript 正则表达式不适用于格式为“(内容)”的字符串

问题描述

我正在尝试使用 JavaScript 的正则表达式函数将我的字符串替换为所需的值。但是当字符串具有这种格式 “(内容)”时,正则表达式一直失败

这是我的正则表达式代码:

     changeFormat = function (oldValue, newValue) {
      var changeData = "http://www.semanticweb.ontology-91#rabindranath_tagore_(film)";
      var regex = new RegExp(oldValue, 'g');
      console.log(regex);
      var source = changeData.replace(regex, newValue);
      console.log(source);
    };
    
    
changeFormat("http://www.semanticweb.ontology-91#rabindranath_tagore_(film)","rabindranath_tagore_(film)");

我的输出是“ http://www.semanticweb.ontology-91#rabindranath_tagore_(film) ”而不是“ rabindranath_tagore_(film)

上述行为是由于括号“()”。

标签: javascriptangularjsregex

解决方案


我认为你需要正确地转义你的字符串。正如您在上面的评论中看到的那样,括号和点( and ) and .在正则表达式中包含特殊含义。

在这里,应该这样做:(来源

function escape(s) {
  return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

这是一个工作片段:

function escape(s) {
  return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

changeFormat = function(oldValue, newValue) {
  var changeData = "http://www.semanticweb.ontology-91#rabindranath_tagore_(film)";
  var regex = new RegExp(escape(oldValue), 'g');
  console.log(regex);
  var source = changeData.replace(regex, newValue);
  console.log(source);
};


changeFormat("http://www.semanticweb.ontology-91#rabindranath_tagore_(film)", "rabindranath_tagore_(film)");


推荐阅读