Javascript replace for all instances - javascript

I found a nice bit of code to add some 'normal' text links (i.e. rather than a button) to share a page on social media sites:
Twitter
Which works great. But for Pinterest I need the url to placed twice, for the page url and for the pin image:
Pinterest
In this case just the first url gets added.
Not that hot on javascript. There must be an easy way to replace all instances of [url], right?

Use a regex with the g (global) modifier
this.href.replace(/\[url\]/g, window.location)

Use a global regexp to match them all:
this.href = this.href.replace(/\[url\]/g, window.location)

Related

Detecting & displaying links in a form's text area

When I enter a link (video, image, URL, etc.) in Facebook's "What's on your mind?" form, it auto-detects the link and converts it to a thumbnail with a brief description below the text-area. Can anyone provide me with insight or a link to get me going on how to achieve this?
There's a javascript attached to the textarea change event. The javascript detects if the content of the textarea is a url, if it is, the javascript call a webservice that visit the url looking for the page title, the page description, etc, (or the open graph protocol meta tags), if it find each one of the tags they are returned to the javascript who proper organize then.
Facebook also cache this content, and if the same url is posted by another user, he uses the cache values instead of revisiting the page.
The open graph protocol meta tags:
http://developers.facebook.com/docs/opengraphprotocol/
using something like
var input = document.getElementById("textarea");
input.addEventListener("change", checkLink(e));
input.addEventListener("blur", checkLink(e));
function checkText(text){
var exp = "((ht|f)tp(s?))(:((\/\/)(?!\/)))(((w){3}\.)?)([a-zA-Z0-9\-_]+(\.(com|edu|gov|int|mil|net|org|biz|info|name|pro|museum|co\.uk)))(\/(?!\/))(([a-zA-Z0-9\-_\/]*)?)([a-zA-Z0-9])+\.((jpg|jpeg|gif|png)(?!(\w|\W)))";
return text.match(exp);
}
function checkLink(e){
//here you would want to use a regular expression and check for http:
var regularExpression = !!checkText(e.target.innerHTML); // returns true or false
if(regularExpression){
e.target.innerHTML += "<a href='#'><img src="" alt="" /></a>";
}
}
good resource for regular expressions - http://regexlib.com/Search.aspx?k=image&c=-1&m=-1&ps=20
Warning -- have to leave for work so regular expressions are not checked.
Take the link value and run it through a regular expression that looks for ^http:...[^\s] or ^https:...[^\s] and returns those.
Then, pass those URLs to your server and have your server retrieve the document and return a snippit for you to then put in your document. You must have your own server to help because Javascript, by itself, has security restrictions. Google same origin policy for more info.

Javascript dynamic link issues?

There might be a duplicate of this (I've tried checking questions on creating dynamic links but they reference a static link - I want this link to be hidden from the user). On testing the following code on the ww3 site:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
document.write("<a href="www.google.com">Google</a>");
</script>
</body>
</html>
I get:
http://www.w3schools.com/jsref/%22www.google.com%22
As the link address rather than www.google.com.
How do I correct this problem? And how do I make it so the link only appears after a set time? Note, this is a simplified version of the code for readability (the dynamic link will including two floating point variables assigned at the time the script is run).
An <a> tag's href must include the protocol http://, otherwise it links to a document relative to the page the link is on:
// Print quote literals, not html entities `"`
document.write("<a href='http://www.google.com'>Google</a>");
The use cases for document.write() are often limited since it can't be used after the page has loaded without overwriting the whole thing. A lot of the time you will want to create the element after the page has already rendered. In that case, you would use document.createElement() and appendChild().
// Create the node...
var newlink = document.createElement('a');
newlink.href = 'http://www.google.com';
// Set the link's text:
newlink.innerText = "Google";
// And add it to the appropriate place in the DOM
// This just sticks it onto the <body>
// You might, for example, instead select a specific <span> or <div>
// by its id with document.getElementById()
document.body.appendChild(newlink);
By the way, w3schools is not affiliated with the W3C, and their examples are generally not recommended since they are often out of date or incomplete.
You have 2 issues:
1) You need http:// before the URL so it's: http://www.google.com
2) You don't need to use quotes in document.write, but if you want to you can do one of these 3:
document.write('Google');
document.write("<a href='http://www.google.com'>Google</a>");
document.write("<a href=http://www.google.com>Google</a>");
Use the slash "\" to escape the quote
To make the link absolute, include the "http://" at the start of the url. Write out:
<a href="http://www.google.com">
instead of
<a href="www.google.com">
The second example will be treated as a relative url, like index.html for example.

Prefixing a URL in an window.open function jQuery

I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.
You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});​
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.
Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});

Where can I find documentation to support this behavior?

I'm looking over some previous developers code and I come across this line:
location.href = '#' + variable;
Which has the effect of updating location.hash. Remove the '#' and of course it redirects to the non-existent url. Playing around a bit it seems I can set the hash via location.href as long as the value starts with '#'. This line or similar is used a lot, but I can't seem to find any documentation the supports this behavior of it updating location.hash by setting location.href this way.
I would like to see something showing this isn't just a happy accident that this works so I don't have to re-code all the situations where this is used. Anything you can link me to would help.
Would it be better to just changes these to properly set the location.hash anyway?
Thnks
At a guess this is because setting location.href to value is supposed to have the same behaviour as clicking a link whose href=value would; it's not supposed to replace the contents of the address bar, because then you'd have to build absolute URLs everytime you wanted to use location.href.
Assigning values to location and location.href was apparently there back in Javascript 1.0, so it's entirely possible this wasn't properly specified anywhere – neither the Mozilla or Microsoft documentation go into detail. HTML5 specifies the behaviour, most likely retroactively.
This is a good place to start your journey on the location properties.
https://developer.mozilla.org/en/window.location
By the way, #something is a valid url and assigning a new url to window.location cause the browser to navigate to the new destination.
#something is called hash and direct the browser to an anchor on the current document, or to the top of the document if the anchor does not exists.
http://docstore.mik.ua/orelly/webprog/DHTML_javascript/0596004672_jvdhtmlckbk-chp-10-sect-2.html
So what happens is when you set location.href to something that is not seen as an absolute path. The browser will automatically put the current url prepended to whatever value you are trying to set it to.
So "#section1" = "www.mysitethatistoocoolforschool.com#section1"
and "section1" = "www.mysitethatistoocoolforschool.comsection1" (this does not exist)
This URLs with a '#' char are called anchor based URLs, they're not supposed to redirect the user from the page, instead they just update the position of the page by some offset, the same way as setting the location.hash you cited.
As stated by Sii this works because when you change the location.href value it's like you're clicking on a link for example then you have the following equivalence:
<a href="#toc" >Go to Table of Contents</a>
Is the same as:
location.href = "#toc";
Both of them would result in your location.hash variable to have the value toc.

Bookmarklet to edit current URL

I'm looking for a simple bookmarklet to take the current URL of my website and refresh it with a couple of changes. For example:
Take the current page: http://www.example.com/pages/
and change it to: https://admin.example.com/pages/
then load that new URL.
I tried searching for a bookmarklet that can do this but I couldn't find one. Can anyone point me in the right direction? Even a bookmarklet that does something like this that I can edit to suit my needs.
Just change window.location, e.g.
window.location=window.location.toString().replace(/^http:\/\/www\./,'https://admin.')
The full bookmarklet would then be:
javascript:(function() {window.location=window.location.toString().replace(/^http:\/\/www\./,'https://admin.');})()
For example you could replace a part of the string using the replace method with a regular expression.
javascript:location = location.href.replace(/http:/g, "https:" )
The above will assign the new string value to the location and trigger the page reload.
This one will change the site name
javascript:(function() {document.title=prompt("Enter Page Title");})();

Categories

Resources