How to extract query string parameters from URL in JavaScript - 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];

Related

How to use regex to match substring via group repeatedly in JavaScript?

For example, I have a string:
var s = "ABCDEFGHIJKLMN";
I would like to get an array of substrings whose length is 1 to 5.
The result I expect is:
["ABCDE", "FGHIJ", "KLMN"]
I tried to get the result via regexp.
Here is my code:
var s = "ABCDEFGHIJKLMN";
var result = s.match(/(.{1,5})+/)
But I can only get the last match of the group instead of all of them:
result[1];
"KLMN"
Use split with a capturing group, and remove the empty strings:
var s = "ABCDEFGHIJKLMN";
var result = s.split(/(.{1,5})/).filter(e => e);
console.log(result);
Add a "g" to the end of the pattern:
var s = "ABCDEFGHIJKLMN";
var result = s.match(/.{1,5}/g)
console.log(result)

Extract words with RegEx

I am new with RegEx, but it would be very useful to use it for my project. What I want to do in Javascript is this :
I have this kind of string "/this/is/an/example" and I would like to extract each word of that string, that is to say :
"/this/is/an/example" -> this, is, an, example. And then use each word.
Up to now, I did :
var str = "/this/is/a/test";
var patt1 = /\/*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
and it returns me : /,,,,,/,,,/,,/,,,,,
I know that I will have to use .slice function next if I can identify the position of each "/" by using search for instance but using search it only returns me the index of the first "/" that is to say in this case 0.
I cannot find out.
Any Idea ?
Thanks in advance !
Use split()
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
var str = "/this/is/a/test";
var array = str.split('/');
console.log(array);
In case you want to do with regex.
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var result = str.match(patt1)
console.log(result);
Well I guess it depends on your definition of 'word', there is a 'word character' match which might be what you want:
var patt1 = /(\w+)/g;
Here is a working example of the regex
Full JS example:
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var match = str.match(patt1);
var output = match.join(", ");
console.log(output);
You can use this regex: /\b[^\d\W]+\b/g, to have a specific word just access the index in the array. e.g result[0] == this
var str = "/this/is/a/test";
var patt1 = /\b[^\d\W]+\b/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
<span id="demo"></span>

regex: get string in url login/test

I have a url
https://test.com/login/param2
how do I get the the second parameter "param2" from the url using REGEX?
the url can also be
https://test.com/login/param2/
So the regex should work for both urls.
I tried
var loc = window.location.href;
var locParts = loc.split('/');
and then looping through locParts, but that seems inefficient.
The "param2" can be have number, alphatical character from a-z, and a dash.
Use String#match method with regex /[^\/]+(?=\/?$)/.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var reg = /[^\/]+(?=\/?$)/;
console.log(
a.match(reg)[0],
b.match(reg)[0]
)
Or using String#split get last non-empty element.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var splita = a.split('/'),
splitb = b.split('/');
console.log(
splita.pop() || splita.pop(),
splitb.pop() || splitb.pop()
)
If you don't mind using JS only (so no regex), you can use this :
var lastParameter = window.location.href.split('/').slice(-1);
Basicaly, like you, I fetch the URL, split by the / character, but then I use the splice function to get teh last element of the split result array.
Regular expressions might be compact, but they're certainly not automatically efficient if you can do what you want without.
Here's how you can change your code:
var loc = 'https://test.com/login/facebook/'; // window.location.href;
var locParts = loc.split('/').filter(function(str) {return !!str});
var faceBookText = locParts.pop();
console.log(faceBookText);
The filter removes the last empty item you would get if the url ends with '/'. That's all you need, then just take the last item.

Javascript Regex replace by group

Suppose you have this string: url?param1=something&param2=something&param3=something which can also be only url?param1=something.
How would you do to convert param1=something to param1=anotherthing ?
I am able to do it this way:
var regex = /param1=.*(&|$)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, 'param1='+newValue);
However, I do not like the fact of repeating all the search term, so I'm asking if it is possible to group the needed pattern to replace, in this case would be .* and replace only that.
For example, saying that $1 belongs to group 1. This is fictitious.
var regex = /param1=(.*)(&|$)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, $1, newValue);
Try this:
var string = 'url?param1=something&param2=something&param3=something';
alert(string.replace(/(param1)([^&]+)/, '$1=newparam1'));
if you want to set multiple parameters to the same value
alert(string.replace(/(param1|param2)([^&]+)/g, '$1=newparam'));
Add another capture group...
var regex = /(param1=)([^&]*)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, "$1" + newValue);

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Categories

Resources