JavaScript - find text in URL by position - javascript

This should be pretty easy but I'm struggling.
I have a button that fires a function. I want an alert to fire as well that tells me which page the user was on.
www.whatever.com/thispage1/whatever
www.whatever.com/thispage2/whatever
www.whatever.com/thispage3/whatever
So after my button is clicked, I want an alert that reads back "thispage1" or "thispage2" etc. I do not want the entire URL fed back to me. Is there a way to find text in a url based on its position or number of characters before it starts?

Look at window.location.pathname and use str.slice to extract the bit you want, with str.indexOf to find the indices to start/end at
var top_dir = window.location.pathname.slice(
1,
window.location.pathname.indexOf('/', 1)
);

Maybe this will help you get started. Key players here are window.location.pathname and string.split()
var returnPage = function() {
var urlString = window.location.pathname;
var stringArray = urlString.split("/");
return stringArray[0]; // number == whichever piece of the array you want to get
};
function myFunction() {
alert(returnPage());
}

Related

Converting Javascript hashtag

What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();

How to detect Links with out anchor element in a plain text

If user enters his text in the text box and saves it and again what's to add some more text he can edit that text and save it if required.
Firstly if user enters that text with some links I, detected them and converted any hyperlinks to linkify in new tab. Secondly if user wants to add some more text and links he clicks on edit and add them and save it at this time I must ignore the links that already hyperlinked with anchor button
Please help and advice
For example:
what = "<span>In the task system, is there a way to automatically have any site / page URL or image URL be hyperlinked in a new window?</span><br><br><span>So If I type or copy http://www.stackoverflow.com/ for example anywhere in the description, in any of the internal messages or messages to clients, it automatically is a hyperlink in a new window.</span><br>http://www.stackoverflow.com/<br> <br><span>Or if I input an image URL anywhere in support description, internal messages or messages to cleints, it automatically is a hyperlink in a new window:</span><br> <span>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</span><br><br>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg<br><br><br><span>This would save us a lot time in task building, reviewing and creating messages.</span>
Test URL's
http://www.stackoverflow.com/
http://stackoverflow.com/
https://stackoverflow.com/
www.stackoverflow.com
//stackoverflow.com/
<a href='http://stackoverflow.com/'>http://stackoverflow.com/</a>";
I've tried this code
function Linkify(what) {
str = what; out = ""; url = ""; i = 0;
do {
url = str.match(/((https?:\/\/)?([a-z\-]+\.)*[\-\w]+(\.[a-z]{2,4})+(\/[\w\_\-\?\=\&\.]*)*(?![a-z]))/i);
if(url!=null) {
// get href value
href = url[0];
if(href.substr(0,7)!="http://") href = "http://"+href;
// where the match occured
where = str.indexOf(url[0]);
// add it to the output
out += str.substr(0,where);
// link it
out += ''+url[0]+'';
// prepare str for next round
str = str.substr((where+url[0].length));
} else {
out += str;
str = "";
}
} while(str.length>0);
return out;
}
Please help
Thanks.
here is a regex where you select all the links without having anchors
(?:(?:http(?:s)?(?:\:\/\/))?(?:www\.)?(?:\w)*(?:\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))
Here is a RegExFiddle (updated 14:41)
quit a lil difficult task because in javascript you don't have a preceded by statement. :)
EDIT1: Now it detects...
http://www.abc.xy
http://abc.xy
https://www.abc.xy
https://abc.xy
www.abc.xy
abc.xy
EDIT2:
Here is it a little shorted and the usage fiddle
Regex
/((http(s)?(\:\/\/))?(www\.)?(\w)*(\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))/g
function
function Linkify(str) {
var newStr = str.replace(/((http(s)?(\:\/\/))?(www\.)?(\w)*(\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))/g,'$1');
return newStr;
}
var newData = Linkify(data);
WORKING JS-FIDDLE
EDIT 1.000.000 :D
/((http(s)?(\:\/\/))?(www\.)?([\w\-\.\/])*(\.[a-zA-Z]{2,3}\/?))(?!(.*a>)|(\'|\"))/g
this solves your problem now.
the only problem you will run in here is, 4 letters after a dot is not selected. e.g .info if you want them selected than change {2,3} to {2,4} BUT be carefully... if someone adds a text like my name is.john than is.john will be translated to a link.
EDIT 2.0
If you have a really complex URL like the following
((http(s)?(\:\/\/))?(www\.)?([\a-zA-Z0-9-_\.\/])*(\.[a-zA-Z]{2,3}\/?))([\a-zA-Z0-9-_\/?=&#])*(?!(.*a>)|(\'|\"))
Matches
https://stackoverflow.com/questions/34170950/summernote-inserthtml?firstname=channaveer&lastname=hakari#fsdfsdf
A more simple solution is probably to strip the links which you created (so the user gets exactly what they typed when they click "Edit" again).
Another idea is to split the string at </a>. That gives you a list of strings which all end with an anchor element (except the last one). Iterate over this list, cut away the part after the last <a, linkify.

Update last path on the URL with javascript

I doing a filter system with pagination and i am in a trouble trying to redirect with Javascript depending on the current URL.
I can have this types of URLs where the last number is a filter:
http://localhost/posts/yourPosts/1
http://localhost/posts/subscriptions/3
And inside each type, page 2 will be shown in this way:
http://localhost/posts/yourPosts/1/page:2?url=posts%2FyourPosts
http://localhost/posts/subscriptions/3/page:2?url=posts%2FSubscriptions
I am currently using:
window.location.href = currentURL + '/' + encodeURI($(this).val());
Where $(this).val is the number of the filter to use.
The problem is that when i am in this URLs it works well:
http://localhost/posts/yourPosts/
http://localhost/posts/subscriptions/
But when i am in the 2nd page and i want to show the filter number 3 (lets say, cars instead of animals), it doesn't. It show this:
http://localhost/posts/subscriptions/2/page:2?url=posts%2FyourPosts/3
Instead of this:
http://localhost/posts/subscriptions/3
Is there any simple way to deal with URLs to solve this kind of problem?
I can not either use an absolute path because the URLs are not all the same. So... is there any way to change the last PATH of a URL?
quick and somewhat dirty:
function fixmybadfilterurl(mybadurl)
{
var parts = mybadurl.split('?');
var subpart2 = parts[parts.length-1].split('/');
var subpart1 = parts[0].split('/');
subpart1.pop();
subpart1.pop();
return(subpart1.join('/')+'/'+subpart2[subpart2.length-1]);
}
so
fixmybadfilterurl('http://localhost/posts/subscriptions/2/page:2?url=posts%2FyourPosts/3');
will return
'http://localhost/posts/subscriptions/3'

Matching a list of possible hashtags in a tweet - Javascript or jQuery

Firstly I've looked at a lot of posts on Stackoverflow but I don't see one which seems to be the definitive way. Someone always seems to find a flaw in the regex.
I already have retrieved my tweets and obviously they can contain any number of hashtags in each one.
If I have an array of possible hashtags that I want to find - ["#ENGLAND","#IRELAND","#wales"] etc.
What is a RELIABLE way to check if a tweet contains these hashtags. I don't want to call the API again, I only want to check my existing tweets, as I'm clicking on buttons to change the filtering on the fly, want to avoid rate limit if they keep clicking around for ages.
EDIT:
Example: Here is a tweet that contains #ENGLAND and #someothertag
I want to search all the tweets and just show the tweets that CONTAIN one or more of my array of tags, I already cache the tweets, I don't want to make a call containing any tags just filter the existing results!
Why only hashify particular hashtags (which you need to specify and then maintain) when you can hashify any hashtag?
I usually use something like this:
var hashregex = /#([a-z0-9_\-]+)/gi,
text = text.replace(hashregex, function (value) {
return '<a target="_blank" href="http://twitter.com/#!/search?q=' + value.replace('#', '%23') + '">' + value + '</a>';
});
Then you can just use text when you set the content to the processed tweets
You could store the hashtags from the entities on the element, for instance
<div class='tweet' data-hashtags='england ireland'>some_tweet</div>
And filter like this when someone clicks your button:
$('div.tweet').hide();
$('div.tweet[data-hashtags~="ireland"]').show();
It's obviously greatly simplified, but the general approach should help you avoid having to parse out the tags yourself
// match a #, followed by either "question" or "idea"
var myregexp = /#(england|ireland|wales)\b/i;
var match = myregexp.exec(subject);
if (match != null) {
result = match[1]; // will contain "england","ireland", or "wales"
} else {
result = "";
}
If you don't know the names of the hashtags on hand
replace
var myregexp = /#(england|ireland|wales)\b/i;
with
var myregexp = /#(\w+)/; // Use this instead

Javascript bookmarklet to click a button found by unique name

I need a javascript bookmarklet which can click on a button. The thing is, there are 100+ buttons on the page all with the same value. The name is unique but quite long.
The full name of the element is something like :
actions[http://apps.facebook.com/frontierville/giftaccept.php?next=giftaccept.php&senderId=1%3A1325206719&gh=3a8bfdace76051752a9127d1f9b43872&gift=nails&timestamp=1285598414&ref=tab&key=29b15e06ed9d7c00a8870c955ab938cf%24%24cfH1PUUZ%217bZYhg8M-o-XQc%218HHRMcvvyhuf4d%21.64qEvlQe&src=request&aff=gift&crt=nails&signature=6dd3fa03fe88f98b6dcab4faf4c7da94]
The value of every button is Accept and Play.
So. Is there a way to have it click on the button with a specific URL in the name?
Here is the source of the info for one of the buttons (got this from chrome's inspect element feature):
<input value="Accept and Play" type="submit" name="actions[http://apps.facebook.com/onthefarm/giftaccept.php?senderId=1259413693&gift=mysterygift&timestamp=1285599906&ref=gift_accept_tab&key=78fcc7de3b36b8f9564262fab506893f%24%24ceK5RVRY61bZYhg8M-o-XQcyL%2CzHccEwEeuj4e-%21-dh0AD0A2AgyScd&signature=32db959ce43f8330cf8fd992fbd53a51&srcapp=FarmVille]">
This should do it...
javascript:var nam=prompt("Give me a URL to look for"); nam="actions["+nam.replace(/\&/g, "&")+"]"; var els=document.getElementsByName(nam); if(els.length == 0) alert("Button not found"); else els[0].click();
It's based on getElementsByName, here it is all spelled out...
var nam = prompt("Give me a URL to look for");
nam = "actions[" + nam.replace(/\&/g, "&") + "]";
var els = document.getElementsByName(nam);
if(els.length == 0)
alert("Button not found");
else
els[0].click();
Here's a rough example of what you might want to do.
var url = 'http://reallylong.facebook.url.from.your.example';
var searchName = 'actions[' + url + ']';
var items = document.getElementsByName(searchName);
if (items.length > 0) {
var myButton = items[0]; // assuming the first item is the correct one
myButton.click(); // programmatically click it
}
if the url is going to change every time, you can find someway to fill the url variable, and use that to generate the element name. This example assumes that element is the only one on the page with that exact name attribute.
This example is pretty rigid and may not work as your bookmarklet if you need to interact with it. What do the other elements look like? Would it be better to look for an element pointing to the giftaccept url or something like that? The script would have a lot more flexibility in a situation like that.
For convenience and compatibility use JQuery selectors:
nameVal = 'actions[http://apps.facebook.com/onthefarm/giftaccept.php?senderId=1259413693&gift=mysterygift&timestamp=1285599906&ref=gift_accept_tab&key=78fcc7de3b36b8f9564262fab506893f%24%24ceK5RVRY61bZYhg8M-o-XQcyL%2CzHccEwEeuj4e-%21-dh0AD0A2AgyScd&signature=32db959ce43f8330cf8fd992fbd53a51&srcapp=FarmVille]'
$("input[value='Accept and Play'][name='" + nameVal + "']").click()

Categories

Resources