Remove all blank values ​​from url

I want to remove all empty values ​​from the URL:

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

Expected Result:

 value1=a&value3=b&value4=c 

I only need the part of the URL request that needs to be considered.

+5
source share
5 answers

Something like that:

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

That is, remove groups of one or more non-equal / non-ampersands characters followed by an equal sign and ampersand or end of line. Then remove the remaining ending ampersands.

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

+9
source

This should do the trick:

 var s="value1=a&value2=&value3=b&value4=c&value5="; var tmp = s.split('&') var newS = ''; for(var i in a) { var t = a[i]; if(t[t.length - 1] !== '=') { newS += t + '&'; } } if(newS[newS.length - 1] === '&') { newS = newS.substr(0, newS.length - 1); } console.log(newS); 
0
source

I cannot find a solution for this with a single Regex expression.

But you can scroll the line and build a new result line: http://jsfiddle.net/UQTY2/3/

 var s="value1=a&value2=&value3=b&value4=c&value5="; var tmpArray = s.split('&'); var final = ''; for(var i=0 ; i<tmpArray.length ; i++) if(tmpArray[i].split('=')[1] != '') final += tmpArray[i] + '&'; final = final.substr(0,final.length-1) alert(final) 
0
source
 s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,""); 

Added by '?' to nnnnnn's answer to fix the problem when the first parameter is empty in the full URL.

0
source

Where do you get all the values? I suggest using an array:

 function getValues(str){ var values = []; var s = str.split('&'); for(var val in s){//source is a var split = val.split('='); if(split [1] != '' && split [1] != null){ values.push(val); } } return values.join('&'); } 
-1
source

All Articles