0

In a node.js server I need to convert URL addresses using JavaScript as follows:

Example 1:

hostA/blah/dir1/name/id.js?a=b --> name.hostC/dir2.js?guid=id&a=b

Example 2:

hostB/dir1/name/id.js --> name.hostC/dir2.js?guid=id

The conversion is done with string.replace using regular expressions detailed inside a configuration file.

So far I have:

url.replace(/.*\\/dir1\\/(.*)\\/\\(d{2})\\.js?:(?=\?)(.*)/, "$1.hostC\/dir2.js?guid=$2");

The replacing string specifies ?guid=id. How do I alter the expression or the replacing string so that &originalQueryString (note the ampersand) will be added in case of example 1 and nothing added in case of example 2?

2
  • Is this what you're looking for? Commented May 19, 2016 at 7:30
  • @ThomasAyoub In the first test case there, it needs to change the second ? to a & (hence the difficulty). Commented May 19, 2016 at 7:31

2 Answers 2

1

This will work for your examples:

text.replace(/.*?\/dir1\/([^\/]+)\/(.*?)\.js\??(.*)/i, "$1.hostC/dir2.js?guid=$2&$3").replace(/&$/, "")

You can change the regex options to include 'g' or 'm', if called for in your implementation.

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't answer my question, but this is what I ended up doing since it looks like a single expression to do what I want is too complex.
0

You can write something like

/([^/]+)\/([^./]+)\.js(?:\?(.*))?$/

Example

> "hostA/blah/dir1/name/id.js".replace(/([^/]+)\/([^./]+)\.js(?:\?(.*))?$/, "$1.hostC/dir2.js?guid=$2&$3")
< "hostA/blah/dir1/name.hostC/dir2.js?guid=id&"

> "hostA/blah/dir1/name/id.js?a=b".replace(/([^/]+)\/([^./]+)\.js(?:\?
(.*))?$/, "$1.hostC/dir2.js?guid=$2&$3")
< "hostA/blah/dir1/name.hostC/dir2.js?guid=id&a=b"

If the trailing & is a problem, you can break the regex into two statements,

< "hostA/blah/dir1/name/id.js".replace(/([^/]+)\/([^./]+)\.js$/, "$1.hostC/dir2.js?guid=$2")
> "hostA/blah/dir1/name.hostC/dir2.js?guid=id"

> "hostA/blah/dir1/name/id.js?a=b".replace(/([^/]+)\/([^./]+)\.js(?:\?(.*))$/, "$1.hostC/dir2.js?guid=$2&$3")
< "hostA/blah/dir1/name.hostC/dir2.js?guid=id&a=b"

7 Comments

They don't want a trailing & in the url. nothing added in case of example 2
What about hostA/blah/dir1/name/id.js?a=b?b=c ?
@ThomasAyoub I assume that is not a valid url
The removal of the trailing & is quite complex to write in a single regex, because it is a new character inserted which you cannot capture from the input string, but have to be derived.
I would suggest a simple if statement that removes any trailing & if it is there. if (url.charAt(url.length - 1) === "&") url = url.substr(0, url.length - 1);
|

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.