Replace all matches except the first one
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 regular expressions in JavaScript? I tried positi开发者_如何学Cve look behind and other methods, but it didn't work for me.
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.
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, '');
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.
精彩评论