javascript - 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) ”
上述行为是由于括号“()”。
解决方案
我认为你需要正确地转义你的字符串。正如您在上面的评论中看到的那样,括号和点( 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)");
推荐阅读
- javascript - 水平菜单悬停延迟 CSS/JS
- excel - 如果条件在另一列中的每个值至少存在一次,则对一列中的值求和
- excel - 将工作簿范围分配给变量 - 类型不匹配
- mongodb - Spring中@Aggregation注解的聚合查询
- database - 是否可以使用无状态逻辑(无数据库)使令牌无效?
- elasticsearch - 在 ELK SIEM 中检测端口扫描后在防火墙上阻止地址 IP
- javascript - 将带有正则表达式的js函数转换为python之一
- python - 在 jupyter notebook Watson IBM Studio 中加载和读取 JSON 文件的文件未找到错误
- python - 向 HTML 显示值,就像在 python 中执行 print() 时值如何在 CMD 提示符中显示一样
- javascript - javascript函数中的axios返回数据