Reputation: 533
Example URL: https://www.example.com/?test=123&[email protected]&xyz=1233 Expected output: https://www.example.com/?test=123&xyz=1233
Basically i am trying to strip the query parameter which containers email ids.
Here is what i have written:
var url = parent.window.location.href.replace('%40', '@').replace('&', '&');
if (url.includes('@') && url.includes('.')) {
var returnurl = '';
var urlParams = new URLSearchParams(url.substring(url.indexOf('?')));
var keys = urlParams.keys();
var entries = urlParams.entries();
for (pair of entries) {
if (!(pair[1].includes('@') && pair[1].includes('.'))) {
if (returnurl != '') {
returnurl = returnurl + '&' + pair[0] + '=' + pair[1];
} else {
returnurl = pair[0] + '=' + pair[1];
}
} else {
url = url.replace(pair[0] + '=' + pair[1], '')
}
}
}
url = url.replace('&&','&');
Is there any better way to manage this? I am looking to write it in pure javascript, so need to remove ECMASCRIPT6 related code(for loop in above sample).
Upvotes: 0
Views: 77
Reputation: 6015
var url = "https://www.example.com/?test=123&[email protected]&xyz=1233"
var path = url.split('?')[0];
var qp = url.split('?')[1];
qp = qp.split('&').filter(function(param) { return param.indexOf('@') === -1} ).join('&');
var result = path+'?'+qp;
console.log(result);
Upvotes: 4
Reputation: 191976
You can use the URL constructor, iterate the URLSearchParams
instance with it's forEach
method, and delete keys that have the @
sign in their value, and then convert the URL back to string:
function stripEmail(urlStr) {
var url = new URL(urlStr);
url.searchParams.forEach(function(value, key) {
if(value.includes('@')) url.searchParams.delete(key);
});
return url.toString();
}
var url = 'https://www.example.com/?test=123&[email protected]&xyz=1233';
var result = stripEmail(url);
console.log(result);
Upvotes: 2