user3612986
user3612986

Reputation: 325

RegExp, JavaScript: Break string at specified characters, encode it, and insert it back in same position

I can't seem to find the correct JavaScript regular expression syntax to take a url string, get characters between other specified characters to encode, then insert back. My example may be easier to explain:

Example:

var url = 'http://www.myurl.com?t=23&dbUrl=http://www.encodeurl.com?t=23&otherUrl=http://www.anotherurl.com'

I need to grab the value between '&dbUrl=' and the next instance of 'http'. Take that value, 'encodeURIComponent' it, then insert it back into the var url to get:

http://www.myurl.com?t=23&dbUrl=http%3A%2F%2Fwww.encodeurl.com%3Ft%3D23%26otherUrl%3Dhttp://www.anotherurl.com

I tried splitting it at any instances of http and just encoding the [1]index of it but I don't always know when in the string '&dbUrl' will exist. I am not looking to break every query parameter but only alter the url between one query parameter and any instance of the next instance of 'http'. Only because the other query param, example used: '&otherUrl=' I wont know the exact query param so I wouldn't know when it stopped unless looking for the http. I will only know the query param of '&dbUrl='. Any ideas?

Upvotes: 1

Views: 61

Answers (1)

Anthony Forloney
Anthony Forloney

Reputation: 91786

One approach would be to leverage the replace functionality to use a function as a second argument to return the transformed string. The return result of the function will end up as the replaced value in the original string,

url.replace(/(&dbUrl=)(.+)(?=http)/,
                     /* 
                      m1 = first matched group
                         e.g, "&dbUrl=http://www.encodeurl.com?t=23&otherUrl="
                      m2 = second matched group
                         e.g, "&dbUrl="
                      m3 = third matched group 
                         e.g, "http://www.encodeurl.com?t=23&otherUrl="
                     */
                 function(m1, m2, m3) {
                    return m2 + encodeURIComponent(m3); 
                 })

// returns,
// "http://www.myurl.com?t=23&dbUrl=http%3A%2F%2Fwww.encodeurl.com%3Ft%3D23%26otherUrl%3Dhttp://www.anotherurl.com"

Upvotes: 1

Related Questions