Using JavaScript and Regex to extract 1 specific data from URL - javascript

I would like to get from an URL like these JUST the "test#gmail.com" (or whatever email will be in the URL) :
www.website.com/?email=test#gmail.com
www.website.com/?email=test#gmail.com&name=john
www.website.com/?name=john&email=test#gmail.com
My problem is to solve that all of these 3 cases can happen (so no other data, OR data after the email, OR data before the email).
Unfortunately I have zero Regex-Skills, but was able to get so far together these 2 things:
/email=(.*)/
/email=(.*)\&/
The 1st one works if the email is the ONLY data.
The 2nd one works just if there is another data after my email.
But as mentioned I need to make it work regardless of which of the 3 types above is the case.
Could you help me out please?
Thank you very much!
BTW, I need it for this:
var msg = window.location.href.match(/email=(.*)/);
(I'm searching for an answer for more than 2 hours, used Google, used Regex-Testers, checked out Cheat Sheets and read many StackOverFlow-Questions... But I can't solve it on my own.)

Try this regex: https://regex101.com/r/gMyqDa/1
It matches email patterns not just any characters after email=

if your cases are that simple, then just exclude the ampersand
var urls = [
"www.website.com/?email=test#gmail.com",
"www.website.com/?email=test#gmail.com&name=john",
"www.website.com/?name=john&email=test#gmail.com"
];
for (i in urls) {
var url = urls[i];
console.log(url);
console.log(url.match(/email=[^&]+/)[0]);
}

Related

Google Scripts extracting a specific ID

I'm trying to figure out how to pull a unique identifier from a Gmail message. I've got the body pulled with:
function myFunction() {
var emails = GmailApp.search('label:company-email subject:"Specific Criteria" ',1,10);
for (x=0;x<emails.length;x++){
var thread = emails[x].getMessages()[0].getPlainBody();
var UID; // need this varible to be set as the extracted UID formatted UID### with 3 possibly 4 numbers. It will always have the same starting "UID"
}
}
UID: need this varible to be set as the extracted UID formatted UID### with 3 possibly 4 numbers. It will always have the same starting "UID"
Edit:
I have researched regex to see if I could get the data with a regular experession, however i'm in over my head there and I'm not understanding it.
I also tried indexOf(), but when I search the thread it gives me a -1. I tested to make sure I had indexOf() correct by testing it with a phrase and the UID, and it pulls when I have a regular string, just not from the body of the email. Maybe I'm missing a conversion somewhere?
Edit #2:
Here is a sample of the email being received:
Good afternoon user,
Please contact *Company Name* (UID123) (*City,State*) (*additional info*) at your earliest convenience.
Thank you,
I deleted the regex and am gonna be honest I don't remember exactly what I tested. was doing that late last night.
Edit 3:
turned out I was doing something wrong with regex. got an answer and I needed the following:
var UID = thread.match("UID[0-9]+"); worked like a charm.
Thank you guys for helping.
Use string#match
\d+ - one or more digits
const msg = `Good afternoon user,
Please contact *Company Name* (UID123) (*City,State*) (*additional info*) at your earliest convenience.
Thank you,`;
console.log(msg.match(/UID(\d+)/)[1])

Passing variables to Javascript from "pretty" URL

My problem is, I would like to create "pretty" URLs for visitors that look like this:
http://domain.com/Name
I have users that often send friends to my service, and I have been created customized pages for each one with the person's First Name in the headline. E.g., "John, here's an easy way to fix this widget"
I then save the page as an index.html file in a custom folder so the link structure for the custom page is domain/Name with Name being their First Name.
This is getting tedious and I would love to use Javascript to automate the process. However, the only documentation I can find on passing variables to Javascript involves "ugly" domains such as domain/jspass2.html?FirstName=John&LastName=Smith
Is there a way to beautify these domains and still pass the variables to a javascript code that inputs their name into the html code? I don't want to "cloak" an ugly domain (using a href, for example)
Thanks for the help!
Well, you could make it "prettier" by making the querystring cleaner.
example:
http://www.domain.com/?John,Smith
The javascript in your index file can read that.
var getQueryString = function() {
queryString = window.location.search;
queryStringCleaned = queryString.substring(queryString.indexOf('?') + 1 );
return queryStringCleaned;
};
if "http://domain.com/Name" is your domain, variable firstName will have the value "Name".
var firstName = window.location.pathname.match(/([\w-]+)\/?.*/)[1];
You could just take the whole URL in JS, and parse it "by hand". Use this regex (for example) to find the parameters passed.
In addition to Paul, I wrote you something that extracts the first name field from the url you provided. If the format is consistent, and you can obtain the url in javascript, you can use this. You may possibly have to create the page first, then redirect the user because javascript is a client side language and the page will already be rendered.
var url = "domain/jspass2.html?FirstName=John&LastName=Smith";
url = url.slice(url.indexOf("FirstName=") + 10, url.length);
url = url.slice(0, url.indexOf("&"));

How to get the domain name using regular expression in javascript?

I have just started to use regular expression and I am finding it difficult to find a regular expression to get the main domain name, that is, if I have urls as given below..
url = http://blog.example.co.in/page/category=?order.php
url = https://www.example.co.ca?page.html
so out of this I want to get only the example out the urls given above. So how can i do it..!!If you can get example in any other method will also be helpful..
I myself tried some methods as given below..
var url = urls.replace('http://','').replace('https://','').replace('www.','').split(/[/?#]/)[0];
var out = url.split('.')[0];
in this I am able to get the output for
https://www.example.co.ca?page.html
but not for
url = http://blog.example.co.in/page/category=?order.php
so can someone help me out a method that can get example out of any kind url
thank you

Passing 2 URL Parameters?

I need to pass 2 URL parameters in a URL. The URL originates in an email and the user will click the link directing them to my site. The first parameter triggers a script on the page the second parameter is for a module my CMS will render from the parameter.
First Parameter is : message=1 (This parameter triggers the javascript)
The second Parameter is: name={tag_recipientfirstname} (My CMS will render the module)
The script that is called for the first looks like this:
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function() {
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('message=1') != -1) {
$j("a.message").colorbox({
open:true
});
}
$j("a.message").colorbox(); //not related to URL parameter
});
</script>
The second parameter is used on the page as:
<div>
<p>{ module_url,name} (again CMS will render this module)</p>
</div>
EDIT
I realize I left a couple things out:
First: How do I pass both parameters so they will both function as listed above?
And the CMS I am using is Business Catalyst.
//split the `location.search` string at the ampersands
var search_arr = window.location.search.replace('?', '').split('&'),
len = search_arr.length,
get_vars = {},
tmp = [];
//iterate through the key/value pairs and add them to the `get_vars` object
for (var i = 0; i < len; i++) {
tmp = search_arr[i].split('=');
get_vars[tmp[0]] = tmp[1];
}
//you can now access your GET variables through the `get_vars` object like: `get_vars.name`
//you can check for the existence of a certain GET variable like this
if (typeof(get_vars['message-1']) != 'undefined') {
$j("a.message").colorbox({
open:true
});
}
Here is a demo:http://jsfiddle.net/aBH8K/1/ (http://jsfiddle.net/aBH8K/1/show/?message-1=3 to see with get var)
Some related documentation:
window.location: https://developer.mozilla.org/en/DOM/window.location
Your question is not so much about generic development, rather a very specific commercial product; I do not know which plan you subscribed (free o pay-for?) with them but in any case it would be best to go through their support (see also my conclusion)
Nevertheless I'll try to put you on the right track.
Your questions
First,
the url in the email
In the email you will have somehow to build a link with the two parameters you want as #Jasper is explaining.
this means something like:
http://yourwebsite.com/destination/path/?message=1&name={tag_recipientfirstname}
Everything after the question mark is a GET query string.
Parameters are separated by the "&" symbol.
I definitely don't know how properly build urls in BC emails, but I feel like it should be an automated somewhere allowing you to specify additional parameters if you need.
the javascript
What you got will still work. It's not very nice, and you can use Jasper's solution or any other such as How can I get query string values in JavaScript?
Nothing to do then unless you want to make it better and more robust.
Business Catalyst (the page)
You usually have ways in a CMS to retrieve get parameters. Often something like
{ GET.param_name }
One step back
I am no expert with BC, but I have the feeling that you are taking a complicate path for something that is probably already baked in.
Again I suggest you go into their support section (though it's rather confusing I must say!) and try to understand what's the best way to achieve your objective. There are always many ways to skin a poor cat.
If you are getting support in your plan, definitely go that way and try to explain what you objectives are rather then how to achieve the technical solution that you think is the good one!

JavaScript To Strip Page For URL

We have a javascript function we use to track page stats internally. However, the URLs it reports many times include the page numbers for search results pages which we would rather not be reported. The pages that are reports are of the form:
http://www.test.com/directory1/2
http://www.test.com/directory1/subdirectory1/15
http://www.test.com/directory3/1113
Instead we'd like the above reported as:
http://www.test.com/directory1
http://www.test.com/directory1/subdirectory1
http://www.test.com/directory3
Please note that the numbered 'directory' and 'subdirectory' names above are just for example purposes and that the actual subdirectory names are all different, don't necessarily include numbers at the end of the directory name, and can be many levels deep.
Currently our JavaScript function produces these URLs using the code:
var page = location.hostname+document.location.pathname;
I believe we need to use the JavaScript replace function in combination with some regex but I'm at a complete loss as to what that would look like. Any help would be much appreciated!
Thanks in advance!
I think you want this:
var page = location.href.substring(0,location.href.lastIndexOf("/"));
You can use a regex for this:
document.location.pathname.replace(/\/\d+$/, "");
Unlike substring and lastIndexOf solutions, this will strip off the end of the path if it consists of digits only.
What you can do is find the last index of "/" and then use the substring function.
Not sure you need a regex if you're just pulling off the last slash + content.
http://www.w3schools.com/jsref/jsref_lastIndexOf.asp
I'd probably use that to search for the last "/" character, then do a substring from the start of the string to that index.
How about this:
var page = location.split("/");
page.pop();
page = page.join("/");
I would think you need to use the .htaccess with rewrite rules to change the look of the url, however I am still looking to see if this is available to javascript. Will repost when I find out more
EDIT*
the lastIndexOf would only give you the position, therefor you would still need to replace. ex:
var temp = page.substring(page.lastIndexOf("/"),page.length-1);
page = page.replace(temp, "");
unfortunately I'm not that advanced in my coding so there is probably more efficient coding in the other answers. Sorry for any inconveniences with my initial answer.

Categories