简体   繁体   中英

Regex Replace $nth element with Javascript

Is it possible that I replace the $n element with a particular string? In my example the $1 element.

For example, i want to replace the last element of a url "http://my.domain.com/sub/file.extension" with my string "other.other" .

my regex is something like this : /([^/]+)\\.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"; 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. 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);

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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