1

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?

user3612986
  • 315
  • 2
  • 7
  • 18
  • 2
    Possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Andreas Oct 09 '15 at 13:17
  • Your `url` variable is broken. Rather than trying to fix it up with clumsy regexps, you should go back to where it is created, and ensure that the that logic escapes `dbUrl` properly when building the URL. –  Oct 09 '15 at 14:57

1 Answers1

1

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"
Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115