Dondey
Dondey

Reputation: 277

Conditionally replacing string with Regular Expression

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?

Upvotes: 0

Views: 85

Answers (2)

Michael Gaskill
Michael Gaskill

Reputation: 8042

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.

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

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"

Upvotes: 0

Related Questions