开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜