Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove all empty values from url

I want to remove all empty values from an url:

var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);

Expected output:

value1=a&value3=b&value4=c

I only need the query part of the URL to be taken into account.

like image 809
Kasper DK Avatar asked Jan 31 '13 11:01

Kasper DK


2 Answers

Something like this:

s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");

That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.

Demo: http://jsfiddle.net/pKHzr/

like image 147
nnnnnn Avatar answered Sep 27 '22 22:09

nnnnnn


s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");

Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.

like image 42
Keith Turkowski Avatar answered Sep 27 '22 21:09

Keith Turkowski