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
source to share
You can use this regex for replacement:
/[^?&=]+=(?:&|$)|&[^?&=]+=(?=&|$)/g
And replace it with:
""
Demo version of RegEx
source to share
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)
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
source to share
Try
/\w+=&|&\w+=$/g,
var url = "http://localhost/wm/frontend/www/?test=&lol=1&boo=2&j=";
document.write(url.replace(/\w+=&|&\w+=$/g, ""))
source to share
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/
source to share