Twitter web intent URL encoding not working - javascript

I have no idea what I'm doing wrong here. I'm trying to encode my URL with javascript. But the URL never gets put into the tweet. I think it has something to do with some parameters in my URL having spaces.
https://twitter.com/intent/tweet?text=40%25%20Off%20Prom%20Tuxedo%20Rental&url=http%3A%2F%2Fexample.com%3A5757%2Fcoupon%3Fref_name%3DTest%20Name%26school%3DTest%20School
If I take out the %20's from my URL then it works...
https://twitter.com/intent/tweet?text=40%25%20Off%20Prom%20Tuxedo%20Rental&url=http%3A%2F%2Fexample.com%3A5757%2Fcoupon%3Fref_name%3DTestName%26school%3DTestSchool
But I need to keep those spaces in there.
This is the javascript code I have right now...
var text = encodeURIComponent("40% Off Prom Tuxedo Rental");
var couponURL = encodeURIComponent("http://example.com/coupon/?ref_name=Test Name&school=Test School");
var twitterURL = "https://twitter.com/intent/tweet?text=";
var twitterURL = twitterURL+text+"&url="+couponURL;

In this situation, a percentage sign equals %25, so if you want to include the spaces in your tweet link, use %2520 instead of %20. So wherever you were going to use %20, use %2520 instead.
var text = "40% Off Prom Tuxedo Rental";
text = text.replace(/\s/g, "%2520")

Related

Replacing separate parts of an URL with Javascript

I'm trying to make a bookmarklet that will take part of an URL and redirect to the new URL, but I need to change two parts of the URL that are separate.
The base URL could be:
78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png
I need it to end like this:
s3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png
So I need to replace "78.media.tumblr.com" and "1280"
I've tried coming up with something using window.location.assign and location.href.replace but I'm pretty new and couldn't figure it out.
You can do this with regex and window.location.href. This is assuming you are only looking at tumbler though. If you're not, there would be another step in the regex.
// first get the url
var url = window.location.href;
// Use regex to keep only the parts we want and replace the others
var newUrl = url.replace(/.*(\.tumblr.*\_).*(\..*)/, 'http://s3.amazonaws.com/data$1raw$2')
// go to the new page
window.location.href = newUrl;
In general, you can just replace the parts of the string using String.prototype.replace. Depending on how flexible you need the matching to be you can adjust the regexes to be more or less 'matchy'.
const startUrl = '78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png'
const endUrl = 's3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png'
const tumblerRegex = /.*\.tumblr\.com/
const numberRegex = /_\d{4}/
function transform (start) {
return start.replace(tumblerRegex, 's3.amazonaws.com/data.tumblr.com').replace(numberRegex, '_raw')
}
console.log(transform(startUrl) == endUrl)

Personalize page content with data passed through a link

I'm building a page for digital campaigns and I'd like to personalize the content of that page based on who referred users there.
For example, A sends B a link to this page, I generate the link to be sent by A automatically on his dashboard. When B clicks the link, I want the page title to say "Hey, A referred you here"
I know the solution to this might be simple but I'm not very awesome with web dev yet. How do I
Pass this information through the link?
Collect the information on the page and put it in as part of the content?
Looking forward to suggestions for most effective implementation
Theory
You can pass information to a page through the URL using URL parameters. This method of posting data is called GET
For example, take this URL:
example.com?key1=val1&key2=val2
You can send any number of parameters using the syntax key=value (note, value is not enclosed in quotes), and separate each one with an &. You must put a question mark between the URL and the parameters.
JavaScript
You can then retrieve the URL parameters using the following JavaScript code. Insert the following at the beginning of your page.
//To get Query Strings with JS
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
To get the value of a URL parameter, do the following:
var x = urlParams.key1; // x will be "val1"
PHP
To retrieve the URL parameters using PHP, it is much simpler. You don't need to add any code to the beginning of the page as with JavaScript, as it is an inbuilt feature of PHP. Just do the following:
$x = $_GET["key1"]; // $x will be "val1"
Practice
In your case, you could make the URL show for user Albert, his unique URL for sharing could be
example.com?sender=Albert
And on your website you could put
<script>
if (urlParams.hasOwnProperty("sender")) {
document.write("Hey, " + urlParams.sender + " reffered you here!");
}
</script>

How to adjust a link using jQuery or Javascript

What I'm trying to do is to change the last character of a link using jQuery or Javascript.
The link that the client will input into the CMS looks something like this: https://www.dropbox.com/sh/wbc1ewhfg1jttpr/AADLfZKlfOBs5e_ueAkzffKRa/SamplePDFDownload.pdf?dl=0
What I'd like to do is to set the website to take this link and replace the '0' on the end of the link with a '1'.
Does anyone know how this could be done automatically?
Any help is appreciated,
Tom
As easy as that:
var url = document.getElementById("id of element").href;
url = url.substring(0, url.length-1);
url = url + "1";
document.getElementById("id of element").href = url;
Probably google first about string functions before asking...
If the pattern of the url stays the same (the parameter dl=0) then you can simply use the .replace()-function:
var url = 'https://www.dropbox.com/sh/wbc1ewhfg1jttpr/AADLfZKlfOBs5e_ueAkzffKRa/SamplePDFDownload.pdf?dl=0';
url = url.replace('dl=0', 'dl=1');

Search for a word and replace everything behind it

I hava a url like
mysite.net/home/index/page/XX
while XX is any number. I need to replace XX and remove everything that might be behind XX. So I would like to remove everything behind page/ by replacing it with a number.
There are a lot of methods for string manipulation http://www.w3schools.com/jsref/jsref_obj_string.asp
I know how to perform this but I am not sure which methods to use. So I ended with getting the lastIndexOf("page/"). So this +1 would give me the starting point for replacing the string. The entire length of the string would be the ending point.
Any ideas?
The following code will do the trick, by using regular expression:
"mysite.net/home/index/page/XX".replace(/\/page\/.*/, '/page/123')
var url = "mysite.net/home/index/page/XX"
return url.substr(-(url.length - (url.lastIndexOf("page/") + 5))))
I don't get your problem because you may have found everything you need...
var yourURI = "mysite.net/home/index/page/XX";
var theDelimiter = "page/";
var yourNewIndex = "42";
var yourNewURI = null;
var lastIndexOfDelimiter = yourURI.lastIndexOf(theDelimiter);
if (lastIndexOfDelimiter != -1)
{
yourNewURI = yourURI.substr(0, lastIndexOfDelimiter + theDelimiter.length) + yourNewIndex;
}
Is that what you want?
This isn't a direct answer to your question, but the way I solve this kind of problem is to have the server calculate a 'base url' (mysite.net/home/index/page/ in your case), and write it to a js variable at the time the page is built.
For two different ASP.NET MVC versions (there would be something similar you could do in any other framework) this looks like this:
var baseUrl = '#ViewBag.BaseUrl';
or
var baseUrl = '<%: ViewData["BaseUrl"] %>';
This has the big advantage that the page JS doesn't start to know about URL formation, so if you change your URL routing you don't find little breakages all over the place.
At least for ASP.NET MVC, you can use the frameworks routing API to generate the base URL at the server side.

How do I trim/strip the URL down to the page name?

How would I go about trimming/stripping the URL down to the page name...
So: http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html
Would become: apage.html
Any ideas?
you do not need jquery:
var url = window.location.href;
var page = url.substring(url.lastIndexOf('/') + 1);
Edit: a good point of the possible query string:
// it might be from browser & / anywhere else
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
ok, if the location object is available, use pathname gives better result as show below, however, a url can be a string or something directly from text field or span/label. So above solution should have its place.
With location and any link (<a>) elements on the page, you get a load of properties that give you specific parts of the URL: protocol, host, port, pathname, search and hash.
You should always use these properties to extract parts of the URL in preference to hacking about with href and probably getting it wrong for corner cases. For example, every solution posted here so far will fail if a ?query or #fragment is present. The answers from Rob and digitalFresh attempt to cope with them, but will still fail if a / character is present in the query string or fragment (which is valid).
Instead, simply:
var pagename= location.pathname.split('/').pop();
Most of the solutions here are not taking advantage of the window.location object. The location object has this wonderful thing called pathname which returns just the path, no query string, host, protocol, hash, etc.
var mypage = window.location.pathname.split("/").pop();
You could do something like this:
document.location.href.split('/').pop();
Edit: you probably want to get rid of the query string if there is one also:
document.location.href.split('/').pop().split('?').shift();
Edit 2: this will also ignore an anchor in the url if there is one
document.location.href.split('/').pop().split(/\?|#/).shift();
This should also exclude query and hash values.
var path = location.href;
path = path.substring(path.lastIndexOf("/") + 1);
path = path.split("?")[0].split("#")[0];
console.debug(path);
Haven't tested so compeltely guessed, but I'm sure something like this will do :-)
var url = 'http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html';
var page = url.split('/');
alert(page[page.length-1]);​
EDIT Tested under jsfiddle and it was wrong, the above code should now work :-)

Categories