How can I edit this code to handle multiple delimiters? Currently, it checks for either %7
or |relevance
and removes it. But it does not handle multiple delimiters such as in the 2 URL examples below.
https://www.example.com/en-us/search?pq=marketing agriculture|relevance|bestSeller:true
https://www.example.com/en-us/search?pq=marketing agriculture|Crelevance|CbestSeller:true
It should only grab the words: marketing agriculture from the two URLs above.
const params = new URLSearchParams(window.location.search);
if (params.has('pq')) {
const pq = params.get('pq').split('&7').pop().replace('|relevance', '');
console.log(pq);
}
Desired output: To get only the search terms from the URL.
CodePudding user response:
Use Regex:
const params = new URLSearchParams(window.location.search);
const regX = /(\w [\ ]?\w )/gm;
if (params.has('pq')) {
const pq = params.get('pq').match(regX);
console.log(pq && pq[0]);
}
CodePudding user response:
You can use the javascript slice method to split the URL and get the search term.
This will work for any search term or any length.
Here is the example:
var str1 = 'https://www.example.com/en-us/search?pq=marketing agriculture|relevance|bestSeller:true';
var str2 = 'https://www.example.com/en-us/search?pq=this is somthing else|Crelevance|CbestSeller:true';
var pattern = /pq=[a-zA-Z 0-9]*/g;
var query1 = str1.match(pattern);
query1 = query1[0].replace('pq=', '').replaceAll(' ', ' ');
console.log(query1);
var query2 = str2.match(pattern);
query2 = query2[0].replace('pq=', '').replaceAll(' ', ' ');
console.log(query2);
For your URL do this: (You may have to change the code according to your need but the basic idea is this itself)
const params = new URLSearchParams(window.location.search);
if (params.has('pq')) {
const pq = params.get('pq').split('|')[0];
console.log(pq);
}
CodePudding user response:
Here is a way to do it:
let a = "https://www.example.com/en-us/search?pq=marketing agriculture|relevance|bestSeller:true"
// Converts Params to Object
const parseParams = (querystring) => {
// parse query string
const params = new URLSearchParams(querystring);
const obj = {};
// iterate over all keys
for (const key of params.keys()) {
if (params.getAll(key).length > 1) {
obj[key] = params.getAll(key);
} else {
obj[key] = params.get(key);
}
}
return obj;
};
let aURL = new URL(a) // get the URL instance
let queryObj = parseParams(aURL.search) // grab and parse the parameter string (.search)
let search = queryObj.pq.split('|')[0] // grab the 'pq' prop (i.e that holds the search value.) and split it to get the actual search string
console.log(search)