简体   繁体   English

正则表达式用Javascript替换$ nth元素

[英]Regex Replace $nth element with Javascript

Is it possible that I replace the $n element with a particular string? 是否可以将$n元素替换为特定的字符串? In my example the $1 element. 在我的示例中, $1元素。

For example, i want to replace the last element of a url "http://my.domain.com/sub/file.extension" with my string "other.other" . 例如,我想用我的字符串"other.other"替换URL "http://my.domain.com/sub/file.extension"的最后一个元素。

my regex is something like this : /([^/]+)\\.extension$ 我的正则表达式是这样的:/([ /([^/]+)\\.extension$

But it also replaces the slash before "file". 但是它也替换了“文件”之前的斜杠。

Here is a complete example: 这是一个完整的示例:

var url = "http://my.domain.com/sub/file.extension";
var replace = "other.other";
var regex = new RegExp("/([^/]+)$");
console.log(url.replace(regex,replace));

I know i could prepend the slash in my replace like this: var replace = "/other.other"; 我知道我可以像这样在替换中添加斜杠: var replace = "/other.other"; but I want a different approach, that I could also use in other Projects. 但是我想要一种不同的方法,也可以在其他项目中使用。

In short, I am looking for a possibility to replace something without the delimiting character to replace with. 简而言之,我正在寻找一种可能的方法,以替换没有分隔符的字符。

PS: I read something about positive lookahead, but I can't get it to work. PS:我读到一些有关积极前瞻的信息,但我无法使其正常工作。 And I know about this Post and this Post , but it's not what I'm looking for. 我知道这则帖子这篇帖子 ,但这不是我想要的。

A small change has been made within your code .try the below code and check 您的代码中进行了少量更改。请尝试以下代码并检查

var url = "http://my.domain.com/sub/file.extension";
var replace = "other.other";
var regex = new RegExp("([^/]+)$");
console.log(url.replace(regex,replace));
var url = "http://my.domain.com/sub/file.extension";
url = url.split("/");
url.pop();
url.push("other.other");
url = url.join("/");
console.log(url);

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM