2

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.

Community
  • 1
  • 1
Nano
  • 1,398
  • 6
  • 20
  • 32

2 Answers2

1

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));
Silz
  • 246
  • 1
  • 5
0
var url = "http://my.domain.com/sub/file.extension";
url = url.split("/");
url.pop();
url.push("other.other");
url = url.join("/");
console.log(url);

enter image description here

Ryan
  • 14,392
  • 8
  • 62
  • 102
  • `url.substring(0, url.lastIndexof('/')+1) + replace` is a bit more compact and does the same. OP stated that he needs a regular expression for some reasons, though. – Ingo Bürk Jun 04 '14 at 08:31