views:

37

answers:

3

I have a malformed URL like this: http://www.abc.com/?abc&?as&?blah

Now, I want to match (and eliminate) all "?" in the URL except the first one to make the URL clean. Is it possible using Regex? I tried positive look behind and other methods, but it didn't work for me.

PS: I need to do this regex operation in JavaScript

+1  A: 

Maybe not the best, but a possible solution: Cut the string in two at the first question mark, remove all the question marks in the second string using regex, glue them back together.

Scytale
+1  A: 
var url = 'http://www.abc.com/?abc&?as&?blah';
var pos = url.search(/\?/) + 1;
var validUrl = url.substr( 0, pos )
             + url.slice( pos ).replace(/\?/g, '');
hsz
+1  A: 

Try this,

var str = "http://www.abc.com/?abc&?as&?blah";
str = str.replace(/(http:\/\/[^\/]+\/\?[^\?]+)\?([^\?]+)\?([^\?]+)/,"$1$2$3");

Tested it in the javascript regular expression tester.

unigg