我可以更换 $n
吗?具有特定字符串的元素?
在我的示例中 $1
元素。
例如,我想替换一个url的最后一个元素
"http://my.domain.com/sub/file.extension"
用我的字符串 "other.other"
.
我的正则表达式是这样的:/([^/]+)\.extension$
但它也替换了"file"之前的斜杠。
这是一个完整的例子:
var url = "http://my.domain.com/sub/file.extension";
var replace = "other.other";
var regex = new RegExp("/([^/]+)$");
console.log(url.replace(regex,replace));
我知道我可以像这样在我的替换中添加斜杠:var replace = "/other.other";
但我想要一种不同的方法,我也可以在其他项目中使用它。
简而言之,我正在寻找一种可能性来替换没有分隔符的东西。
附言: 我读了一些关于积极前瞻的东西,但我无法让它发挥作用。 我知道 this Post和 this Post ,但这不是我要找的。p>
最佳答案
在您的代码中做了一个小改动。尝试下面的代码并检查
var url = "http://my.domain.com/sub/file.extension";
var replace = "other.other";
var regex = new RegExp("([^/]+)$");
console.log(url.replace(regex,replace));
关于javascript - 正则表达式用 Javascript 替换第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24032245/