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.

1
  • Just for explanation: I deleted my answer as other answers have been added while I fixed mine. Commented Jun 4, 2014 at 8:30

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.