Replace the some special symbol from query string in javascript - javascript

I want to get these type of params PropertyType[] in my url instead of PropertyType[0].How to replace it?
Actual URL
City=Antwerp,Archbold,Berkey&PropertyType[0]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000
I want these type of url
City=Antwerp,Archbold,Berkey&PropertyType[]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000
var serializeData = $('#searchstring').val();
console.log(serializeData);
var data = JSON.stringify(serializeData);
var url1 = data.replace(/['"]/g,'');
var url = url1.replace(/\+/g,' ');
var uri_dec = decodeURIComponent(url);

You can use \d regular expression to replace all digits that appear in []
var url = 'City=Antwerp,Archbold,Berkey&PropertyType[0]=Residential&minbed=1&minbath=1&min_price=10000&max_price=2500000';
var regEx = new RegExp(/\[\d+\]/,'gim');
var newURL = url.replace(regEx, (match) => '[]');
console.log(newURL)

you can replace these using regex in js
url = ""your_url"
new_url = url.replace(/([\d])/g, '')

Related

Extract id from url string

I want to extract the id 1406570408 from the below url. I was wondering if there is a better way than my current try ?
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
str = str.split('/')
str = str[5].split('?')
console.log(str[0]) // 1406570408
how about using url class ?
let url = new URL("https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013")
url.pathname.split('/')[3] //equals the id
here
url.pathname contains webapp/viewer/1406570408
or use
url.pathname.split('/').pop() to remove the last element as #O.Jones pointed out
const url = "https://www.google.de/webapp/viewer/1406570408?pag…-P-Global_Startpage&lat=52.5517268&lng=13.4123013"
const url2 = "https://www.google.de/webapp/viewer/1406570408"
const url3 = "https://www.google.de/webapp/something/1406570408"
const getId = (url) => {
const match = /(?<=viewer\/)\d*/.exec(url)
return match ? match[0] : null;
}
console.log(getId(url))
console.log(getId(url2))
console.log(getId(url3))
let url = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
const segments = new URL(url).pathname.split('/');
const last = segments.pop() || segments.pop();
console.log(last);
Here is the single line plain javascript methods of Arrays
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
str = str.split('?')[0].split('/').reverse()[0]
console.log(str) // 1406570408
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
console.log(str.match(/\d+/)[0]);
Use an regrex to find an numeric value inside a url string
Best way is to parse the URL with the URL JavaScript API, and then extract the piece of data you need from the pathname property provided to you by the URL.
An example for your usecase:
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
let url = new URL(str); // create an instance of the URL API
let pathname = url.pathname; // pathname property
let segments = pathname.split('/'); // split pathname by / slash
let last_item = segments.slice(-1)[0] || null; // grab the last item from pathname array
console.log(last_item);
Your output will be: 1406570408.
If your pathname is '/' or no pathname at all, you'll receive a null which you can handle later.
Also, the above code could be shortened into:
let str = 'https://www.google.de/webapp/viewer/1406570408?page=1&pageType=DE-P-Global_Startpage&lat=52.5517268&lng=13.4123013';
let last_item = (new URL(str)).pathname.split('/').slice(-1)[0] || null;
console.log(last_item);

How to extract query string parameters from URL in JavaScript

I have a URL
https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama
I want to get search_terms (Generator+Repair) and geo_location_terms (Adamsville%2C+Alabama)
How I can do this?
The easiest and most idiomatic way to do this in JavaScript is using the URL class:
const url = new URL('https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama')
console.log(url.searchParams.get('search_terms'));
console.log(url.searchParams.get('geo_location_terms'));
MDN reference here.
You can use the following Javascript code to store the GET parameters into an object:
<script>
var URL = "https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama";
var result = {};
URL.substring(URL.indexOf("?") + 1).split('&').forEach(function(x){
var arr = x.split('=');
arr[1] && (result[arr[0]] = arr[1]);
});
console.log(result.search_terms);
//OUTPUT: "Generator+Repair"
console.log(result.geo_location_terms);
//OUTPUT: "Adamsville%2C+Alabama"
</script>
You can use the following regex to get the 2 values:
/search_terms=(.*)&geo_location_terms=(.*)/
This is a very basic regex, that starts by matching 'search_terms=' then creates a Group that matches any number of any char up to the '&' sign, then matches 'geo_location_terms=' and finally creates a Group that matches any number of any char.
Your desired output will be in Group 1 and Group 2.
How to use:
var url = 'https://www.yellowpages.com/search?search_terms=Generator+Repair&geo_location_terms=Adamsville%2C+Alabama';
var regex = /search_terms=(.*)&geo_location_terms=(.*)/;
var match = url.match(regex);
var search_terms = match[1];
var geo_location_terms = match[2];

Regex to get a specific parameter from a URL

assume that we have a URL like this
http://localhost:8080/dev.html?organization=test&location=pr&lang=fr
I'd like to make a regex that takes the organization=test only so that I store it into a var.
So in case I have http://localhost:8080/dev.html?organization=test, I get the organization=test.
http://localhost:8080/dev.html?lang=fr&organization=test, I get organization=test.
No matter how the URL is formed or the order of the parameters, I get
organization=<organization>
Thank you
Why use RegEx or split ? Try this:
function getOrganization(){
return new URLSearchParams(location.search).get('organization')
}
(requires a polyfill for the URL API in IE)
You can use this function, assuming the parameter name does not even if the parameter does contain any characters considered special within RegExp:
function getParam(url, name, defaultValue) {
var a = document.createElement('a');
a.href = '?' + unescape(String(name));
var un = a.search.slice(1);
var esc = un.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&');
var re = new RegExp('^\\?&*(?:[^=]*=[^&]*&+)*?(' + esc + ')=([^&]*)');
a.href = url;
var query = a.search;
return re.test(query) ? query.match(re).slice(1).map(decodeURIComponent) : [un, defaultValue];
}
var url = 'http://localhost:8080/dev.html?lang=fr&organization=test&crazy^ ()*key=cool';
console.log(getParam(url, 'organization'));
console.log(getParam(url, 'lang'));
console.log(getParam(url, 'crazy^ ()*key'));
console.log(getParam(url, escape('crazy^ ()*key')));
console.log(getParam(url, encodeURIComponent('crazy^ ()*key')));
console.log(getParam(url, 'foo', 'bar'));
RegExp escape method borrowed from How to escape regular expression in javascript?
Usage
getParam(url, name[, defaultValue])
url - A well-formed URL
name - The parameter name to search
defaultValue (optional) - If not found, what value to default to. If not specified, defaultValue is undefined
return - [ unescape(name), found ? stringValue : defaultValue ]
Why use regex? Try this.
function getOrganization(){
var params = location.search.split('?')[1].split('&');
for(var i = 0; i < params.length; i++){
if(params[i].split('=')[0] == 'organization') return params[i].split('=')[1];
}
}

Regex not working to remove string/whatever

How can I remove this string from href and update it ?
Example Url:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People"
What I am trying:
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace('/(' + stringToRemove + '\/\w+,)/g', '');
$("#qUrl").attr("href", url);
What I want:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,ID,People/FirstName,People/LastName&$expand=People"
Update
Please don't hard code
If you are looking to remove all Products/..., than RegEx is /Products\/.*?,/g
Take a note that RegExp is written as is - without surrounding it with quotes.
var str = 'localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People';
console.log(str.replace(/Products\/\w+,?/g, ''));
/**
* Replace with variable string
*/
var key = 'Products'; // Come from external source, not hardcoded.
var pattern = new RegExp(key+'/\\w+,?', 'g'); // Without start and end delimiters!
console.log(str.replace(pattern, ''));
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace(/Products\/Name,/g, '');
$("#qUrl").attr("href", url);
Modify the replace call , use regex without quotes

Regex for URL with querystring

I use the following javascript with regex to test url string.
var url = window.location.pathname;
// create regexp to match current url pathname and remove trailing slash if
// present as it could collide with the link in navigation in case
// trailing slash wasn't present there
urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/, ''));
// now grab every link from the navigation
$('.page-sidebar a').each(function () {
// and test its normalized href against the url pathname regexp
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).closest("li").addClass("active");
}
});
But this regex doesnt include the querystring. How can I do that?
Perhaps you could match a string with something like this and construct from it what you want.
var rx = new RegExp("^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:#]*)(?::([^:#]*))?)?#)?([^:\\/?#]*)(?::(\\d*))?))?((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)");
var url = "http://stackoverflow.com/questions/16053753/regex-for-url-with-querystring?a0b&c=d&e=f#anchor";
var val = url.match(rx);
val.forEach(function (part) {
var result = $("#result");
var $text = $("<p>").text(part);
result.append($text);
});
You can play with this code on jsfiddle

Categories

Resources