Remove all empty values ​​from url string

I am trying to remove all empty params from url string. My url looks like this

http://localhost/wm/frontend/www/?test=&lol=1&boo=2

my code should return

http://localhost/wm/frontend/www/?lol=1&boo=2

but instead it returns

http://localhost/wm/frontend/www/?&lol=1&boo=2

This is the regex I'm using replace("/(&?\w+=((?=$)|(?=&)))/g","")

, I know I can just use strings replace()

that match '? & 'after 1st replacement, but I'd rather edit my regex to do that, so it's in 1 line of code. Any ideas?

here is my jsfiddle

+3


source to share


4 answers


You can use this regex for replacement:

/[^?&=]+=(?:&|$)|&[^?&=]+=(?=&|$)/g

      

And replace it with:



""

      

Demo version of RegEx

+1


source


You can, for example, say:

var s = 'http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=';
s = s.replace(/\w*=\&/g, '');
s = s.replace(/&\w*=$/g, '');

      

That is, remove the letters

+ =

+ block &

. Then remove the &

+ letters

+ =

at the end of the line (denoted by a symbol $

).

To enter, enter:

http://localhost/wm/frontend/www/?lol=1&boo=2

      

See the JSFiddle or right here:



var s = 'http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=';
s = s.replace(/\w*=\&/g, '');
s = s.replace(/&\w*=$/g, '');
document.write(s)
      

Run codeHide result


Test

If the input contains blocks in the middle and at the end:

http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=

      

the code I wrote above returns:

http://localhost/wm/frontend/www/?lol=1&boo=2

      

0


source


Try

/\w+=&|&\w+=$/g,

      

var url = "http://localhost/wm/frontend/www/?test=&lol=1&boo=2&j=";
document.write(url.replace(/\w+=&|&\w+=$/g, ""))
      

Run codeHide result


0


source


Just try calling native 'replace', which can be used with regex in its first argument.

str.replace(regex, replace_str)

      

Please have a look at this fiddle to see an example: http://jsfiddle.net/xvqasgmu/1/

0


source







All Articles