Capture value out of query string with regex? - javascript

I am trying to select just what comes after name= and before the & in :
"/pages/new?name=J&return_url=/page/new"
So far I have..
^name=(.*?).
I am trying to return in this case, just the J, but its dynamic so it could very several characters, letters, or numbers.
The end case situation would be allowing myself to do a replace statement on this dynamic variable found by regex.

/name=([^&]*)/
remove the ^ and end with an &
Example:
var str = "/pages/new?name=J&return_url=/page/new";
var matches = str.match(/name=([^&]*)/);
alert(matches[1]);
The better way is to break all the params down (Example using current address):
function getParams (str) {
var queryString = str || window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.replace(/.*?\?/,"");
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
return params;
}
var url = "/pages/new?name=L&return_url=/page/new";
var params = getParams(url);
params['name'];
Update
Though still not supported in any version of IE, URLSearchParams provides a native way of retrieving values for other browsers.

The accepted answer includes the hash part if there is a hash right after the params. As #bishoy has in his function, the correct regex would be
/name=([^&#]*)/

Improving on previous answers:
/**
*
* #param {string} name
* #returns {string|null}
*/
function getQueryParam(name) {
var q = window.location.search.match(new RegExp('[?&]' + name + '=([^&#]*)'));
return q && q[1];
}
getQueryParam('a'); // returns '1' on page http://domain.com/page.html?a=1&b=2

here is the full function (tested and fixed for upper/lower case)
function getParameterByName (name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name.toLowerCase() + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search.toLowerCase());
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}

The following should work:
\?name=(.*?)&

var myname = str.match(/\?name=([^&]+)&/)[1];
The [1] is because you apparently want the value of the group (the part of the regex in brackets).
var str = "/pages/new?name=reaojr&return_url=/page/new";
var matchobj = str.match(/\?name=([^&]+)&/)[1];
document.writeln(matchobj); // prints 'reaojr'

Here's a single line answer that prevents having to store a variable (if you can't use URLSearchParams because you still support IE)
(document.location.search.match(/[?&]name=([^&]+)/)||[null,null])[1]
By adding in the ||[null,null] and surrounding it in parentheses, you can safely index item 1 in the array without having to check if match came back with results. Of course, you can replace the [null,null] with whatever you'd like as a default.

You can get the same result with simple .split() in javascript.
let value = url.split("name=")[1].split("&")[0];

This might work:
\??(.*=.+)*(&.*=.+)?

Related

Javascript how to remove parameter from URL sting by value?

How to remove parameters with value = 3 from URL string?
Example URL string:
https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3
If you are targeting browsers that support URL and URLSearchParams you can loop over the URL's searchParams object, check each parameter's value, and delete() as necessary. Finally using URL's href property to get the final url.
var url = new URL(`https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3`)
//need a clone of the searchParams
//otherwise looping while iterating over
//it will cause problems
var params = new URLSearchParams(url.searchParams.toString());
for(let param of params){
if(param[1]==3){
url.searchParams.delete(param[0]);
}
}
console.log(url.href)
There is a way to do this with a single regex, using some magic, but I believe that would require using lookbehinds, which most JavaScript regex engines mostly don't yet support. As an alternative, we can try splitting the query string, then just examining each component to see if the value be 3. If so, then we remove that query parameter.
var url = "https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3";
var parts = url.split(/\?/);
var params = parts[1].replace(/^.*\?/, "").split(/&/);
var param_out = "";
params.forEach(function(x){
if (!/.*=3$/.test(x))
param_out += x;
});
url = parts[0] + (param_out !== "" ? "?" + param_out : "");
console.log(url);
You could use a regular expression replace. Split off the query string and then .replace &s (or the initial ^) up until =3s:
const str = 'https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3';
const [base, qs] = str.split('?');
const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
const output = base + (replacedQs ? '?' + replacedQs : '');
console.log(output);

How to remove `&` sign and all text after that from url

I have this URL
https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request
Here I am getting sys_id two times with different parameters. So I need to remove the second & sign and all text after that.
I tried this
location.href.split('&')[2]
I am sure it doesn't work. Can anyone provide some better solution?
Firstly, you should split the string into an array then use slice to set the starting index number of the element which is 2 in your case and then join the array again into the string.
Read more about these methods JavaScript String split() Method, jQuery slice() Method and JavaScript Array join() Method
var url = 'https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
url = url.split("&").slice(0,2).join("&");
console.log(url);
Maybe like this:
var url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
var first=url.indexOf('&');
var second=url.indexOf('&',first+1);
var new_url=url.substring(0,second);
console.log(new_url);
You need to find the 2nd occurrence of &sys_id. From there onwards remove all text.
Below is working code:
let url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
let str1=url.indexOf('&sys_id');
let str2=url.indexOf('&sys_id',str1+1);
console.log(url.substring(0,str2));
This is a bit more verbose, but it handles all duplicate query params regardless of their position in the URL.
function removeDuplicateQueryParams(url) {
var params = {};
var parsedParams = '';
var hash = url.split('#'); // account for hashes
var parts = hash[0].split('?');
var origin = parts[0];
var retURL;
// iterate over all query params
parts[1].split('&').forEach(function(param){
// Since Objects can only have one key of the same name, this will inherently
// filter out duplicates and keep only the latest value.
// The key is param[0] and value is param[1].
param = param.split('=');
params[param[0]] = param[1];
});
Object.keys(params).forEach(function(key, ndx){
parsedParams += (ndx === 0)
? '?' + key +'='+ params[key]
: '&' + key +'='+ params[key];
});
return origin + parsedParams + (hash[1] ? '#'+hash[1] : '');
}
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff') );
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff#withHash') );
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
url = url.slice(0, url.indexOf('&', url.indexOf('&') + 1));
console.log(url);
Try this :)
Try this:
var yourUrl = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
var indexOfFirstAmpersand = yourUrl.search("&"); //find index of first &
var indexOfSecondAmpersand = indexOfFirstAmpersand + yourUrl.substring((indexOfFirstAmpersand + 1)).search("&") + 1; //get index of second &
var fixedUrl = yourUrl.substring(0, indexOfSecondAmpersand)
$(".answer").text(fixedUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="answer">
</p>
You can manipulate the url using String.prototype.substring method. In the example below I created a function that takes a url string and checks for a duplicate parameter - it returns a new string with the second occurrence removed.
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request";
function stripDuplicateUrlParameter(url, parameterName) {
//get the start index of the repeat occurrance
var repeatIdx = url.lastIndexOf('sys_id');
var prefix = url.substring(0, repeatIdx);
var suffix = url.substring(repeatIdx);
//remove the duplicate part from the string
suffix = suffix.substring(suffix.indexOf('&') + 1);
return prefix + suffix;
}
console.log(stripDuplicateUrlParameter(url));
This solves your specific problem, but wouldn't work if the parameter occurred more than twice or if the second occurrence of the string wasn't immediately following the first - you would probably write something more sophisticated.
As someone already asked - why is the url parameter being duplicated in the string anyway? Is there some way to fix that? (because the question asked seems to me to be a band-aid solution with this being the root issue).

Update uri hash javascript

I find it hard to believe this hasn't been asked but I can find no references anywhere. I need to add a URI hash fragment and update the value if it already is in the hash. I can currently get it to add the hash but my regex doesn't appear to catch if it exists so it adds another instead of updating.
setQueryString : function() {
var value = currentPage;
var uri = window.location.hash;
var key = "page";
var re = new RegExp("([#&])" + key + "=.*#(&|$)", "i");
var separator = uri.indexOf('#') !== -1 ? "&" : "#";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
},
Also if this can be made any cleaner while preserving other url values/hashes that would be great.
example input as requested
Starting uri value:
www.example.com#page=1 (or no #page at all)
then on click of "next page" setQueryString gets called so the values would equal:
var value = 2;
var uri = '#page1'
var key = 'page'
So the hopeful output would be '#page2'.
As to your regex question, testing if the pattern #page=(number) or &page=(number) is present combined with capturing the number, can be done with the regex /[#&]page\=(\d*)/ and the .match(regex) method. Note that = needs escaping in regexes.
If the pattern exists in the string, result will contain an array with the integer (as a string) at result[1]. If the pattern does not exist, result will be null.
//match #page=(integer) or &page=(integer)
var test = "#foo=bar&page=1";
var regex = /[#&]page\=(\d*)/;
var result = test.match(regex);
console.log(result);
If you want to dynamically set the key= to something other than "page", you could build the regex dynamically, like the following (note that backslashes needs escaping in strings, making the code a bit more convoluted):
//dynamically created regex
var test = "#foo=bar&page=1";
var key = "page"
var regex = new RegExp("[#&]" + key + "\\=(\\d*)");
var result = test.match(regex);
console.log(result);

Javascript Regex Search

I generated the following code through a website. What I am looking for is that the script scans through a text variable against a set of keywords, and if it finds any of the keywords, it passes it to a variable. And if two keywords are found, both are joined by a hyphen and passed to a variable. I also need to set the "var str" dynamically. For instance, "var str == VAR10." VAR10 will have a dynamic text to be searched for keywords.
var re = /Geo|Pete|Rob|Nick|Bel|Sam|/g;
var str = 'Sam maybe late today. Nick on call. ';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}
In the above code, Sam and Nick are two keywords that I want hyphenated and passed to VAR10.
If two keywords are found, both are joined by a hyphen and passed to a
variable
Try this update to your original code for clarity:
var re = /Geo|Pete|Rob|Nick|Bel|Sam/g;
var str = 'Sam maybe late today. Nick on call. ';
var m;
var VAR10 = ""; // holds the names found
if ((m = re.exec(str)) !== null) {
var name1 = m;
if ((m = re.exec(str)) !== null) {
var name2 = m;
// Two names were found, so hyphenate them
// Assign name1 + "-" + name2 to the var that you want
VAR10 = name1 + "-" + name2;
} else {
// In the case only one name was found:
// Assign name1 to the var that you want
VAR10 = name1;
}
}
Note, change
var re = /Geo|Pete|Rob|Nick|Bel|Sam|/g;
to
var re = /Geo|Pete|Rob|Nick|Bel|Sam/g;
Here is an updated demo: http://jsfiddle.net/7zg2hnt6/1/
You can "capture" names with parenthesis:
/(Geo|Pete|Rob|Nick|Bel|Sam)/g
A sample: https://regex101.com/r/eK5hY2/1
To return the first two names found in hyphenated fashion:
str.match(re) . slice(0, 2) . join('-')
You have an extra | at the end of your regexp, which is likely to result in matches on an empty string. Remove it.
I also need to set the "var str" dynamically. For instance, "var str == VAR10." VAR10 will have a dynamic text to be searched for keywords.
var str == VAR10 is invalid syntax. I'll assume you mean var str = VAR10;. That's just a plain old variable assignment. All assignments in JS are "dynamic" by definition and happen at run-time. This would seem to have nothing to do with your specific problem.
Your code is almost doing what you want.
First you need to capture your matches, then join them.
http://jsfiddle.net/c6tjk21d/1/
var re = /(Geo|Pete|Rob|Nick|Bel|Sam)/g;
var str = 'Sam maybe late today. Nick on call. ';
var VAR10 = str.match(re).join('-')
console.log(VAR10);
I don't think you want to use exec because it maintains state and I've found it to be unintuitive. For example, in order to get more than one match with the code you've written, you'll need to loop through resulting on exec. Check out MDN for examples if you're interested. I almost always prefer match().

Regex string ends with not working in Javascript

I am not very familiar with regex. I was trying to test if a string ends with another string. The code below returns null when I was expecting true. What's wrong with the code?
var id = "John";
var exists ="blahJohn".match(/id$/);
alert(exists);
Well, with this approach, you would need to use the RegExp constructor, to build a regular expression using your id variable:
var id = "John";
var exists = new RegExp(id+"$").test("blahJohn");
alert(exists);
But there are plenty ways to achieve that, for example, you can take the last id.length characters of the string, and compare it with id:
var id = "John";
var exist = "blahJohn".slice(-id.length) == id; // true
You would need to use a RegExp() object to do that, not a literal:
var id = "John",
reg = new RegExp(id+"$");
alert( reg.test("blahJon") );
That is, if you do not know the value you are testing for ahead of runtime. Otherwise you could do:
alert( /John$/.test("blahJohn") );
Try this -
var reg = "/" + id + "$/";
var exists ="blahJohn".match(reg);
The nicer way to do this is to use RegExp.test:
(new RegExp(id + '$')).test('blahJohn'); // true
(new RegExp(id + '$')).test('blahJohnblah'); // false
Even nicer would be to build a simple function like this:
function strEndsWith (haystack, needle) {
return needle === haystack.substr(0 - needle.length);
}
strEndsWith('blahJohn', id); // true
strEndsWith('blahJohnblah', id); // false
var id = new RegExp("John");
var exists ="blahJohn".match(id);
alert(exists);
try this
I like #lonesomeday 's solution, but Im fan of extending the String.prototype in these scenarios. Here's my adaptation of his solution
String.prototype.endsWith = function (needle) {
return needle === this.substr(0 - needle.length);
}
So can be checked with
if(myStr.endsWith("test")) // Do awesome things here.
Tasty...
var id = "John";
(new RegExp(`${id}$`)).test('blahJohn'); // true
(new RegExp(`${id}$`)).test('blahJohna'); // false
`${id}$` is a JavaScript Template strings which will be compiled to 'John$'.
The $ after John in RegExp stands for end of string so the tested string must not have anything after id value (i.e. John) in order to pass the test.
new RegExp(`${id}$`) - will compile it to /John$/ (so if id shouldn't be dynamic you can use just /John$/ instead of new RegExp(`${id}$`) )
Why using RegExp? Its expensive.
function EndsWith( givenStr, subst )
{
var ln = givenStr.length;
var idx = ln-subst.length;
return ( giventStr.subst(idx)==subst );
}
Much easier and cost-effective, is it?
If you need it for replace function, consider this regExp:
var eventStr = "Hello% World%";
eventStr = eventStr.replace(/[\%]$/, "").replace(/^[\%]/, ""); // replace eds with, and also start with %.
//output: eventStr = "Hello% World";
2022, ECMA 11
Just created this helper function, I find it more useful and clean than modifying the regex and recreating one everytime.
/**
* #param {string} str
* #param {RegExp} search
* #returns {boolean}
*/
function regexEndsWith (str, search, {caseSensitive = true} = {})
{
var source = search.source
if (!source.endsWith('$')) source = source + '$'
var flags = search.flags
if (!caseSensitive && !flags.includes('i')) flags += 'i'
var reg = new RegExp(source, flags)
return reg.test(str)
}
Use it this way:
regexEndsWith('can you Fi nD me?', /fi.*nd me?/, {caseSensitive: false})
Here is a string prototype function that utilizes regex. You can use it to check if any string object ends with a particular string value:
Prototype function:
String.prototype.endsWith = function (endString) {
if(this && this.length) {
result = new RegExp(endString + '$').test(this);
return result;
}
return false;
}
Example Usage:
var s1 = "My String";
s1.endsWith("ring"); // returns true;
s1.endsWith("deez"); //returns false;

Categories