I'm struggling with what is probably a very simple regex problem. I'm working on a simple prototype and need to know what page I'm on, so I don't reload it if the user clicks a menu widget to navigate to the same view.
I have two URLs the user can switch between:
http://localhost/TestMVC/Larry/LarryTiles
http://localhost/TestMVC/Larry/LarryTilesList
The URLs can also have some trailing querystring items, like this:
http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers
LarryTiles is giving me the problem. "/\bLarryTiles\b/" worked on Friday (after answers from other questions here) but this doesn't match now. :)
I need to find exactly the strings "LarryTiles" and "LarryTilesList" in these two URLs but can't quite figure out how to do that. The URL changes between my local machine and the various servers where it's hosted, so I can't rely on position.
EDIT: added the example with a trailing querystring, which I'd forgotten. Sorry :(
You can get the last path segment of an URL like this:
function getLastPathSegment(url) {
var match = url.match(/\/([^\/]+)\/?$/);
if (match) {
return(match[1]);
}
return("");
}
// returns "LarryTiles"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTiles");
// returns "LarryTilesList"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTilesList");
So, you could do this:
var endPath = getLastPathSegment(window.location.pathname);
if (endPath == "LarryTiles") {
// some code
} else if (endPath == "LarryTilesList") {
// some code
} else {
// some code
}
You can use this code:
str = 'http://localhost/TestMVC/Larry/LarryTiles?filterValue=servers';
if (str.match(/\/([^\/?]+)(?=\/$|\?|$)/)) {
if (match[1] == 'LarryTiles')
alert('LarryTiles found');
else if (match[1] == 'LarryTilesList')
alert('LarryTilesList found');
}
Seems like what you explained works, otherwise try this: http://jsfiddle.net/Wfz9d/
Do you have a case-sensitivity issue?
Related
Sorry i cant find the tutorial in google because i dont know the keyword...
var currentURL=location.href;
var str = currentURL;
if(str == "http://web.com/blabla" || str == "http://web.com/bleble"){
window.location = "http://web.com/ban";
} else {
}
How to make str == "http://web.com/blabla" || str == "http://web.com/bleble" to list ? so if i want to input some url again, i just input the url to the list. Can give me the code or link tutorial ???
Basically you'll need to place all of your URL's into an array and then iterate over the array checking each item.
var urls = ['http://web.com/','http://web.net/','http://web.org'];
var current_url = '...';
for (var i = 0; i < urls.length; i++){
if (current_url == urls[i]){
window.location = "http://web.com/ban";
break; // exit the loop since we have already found a match
}
}
The break command will terminate the loop and stop searching the array for matching URLs. Since the action you want to take needs to happen if any of the URLs match, it's enough for one to match in order to stop searching.
Lists are called arrays in javascript, and are declared using square brackets, like this: var badUrls = ["http://web.com/blabla", "http://web.com/bleble"].
To check whether the current URL appears in the array, you can use the .indexOf function of the array, which will return the first position in the array where the string you provide can be found (starting with 0 for the first element), or -1 if it doesn't exist. For example, if you have an array var arr = ["foobar", "foo", "bar", "baz"], and you do arr.indexOf("foo"), you get 1 because it's the 2nd element in the array. If instead you do arr.indexOf("fooba"), you will get -1 because none of the elements in the array are fooba exactly. In your code, you want to redirect the user if badUrls.indexOf(str) > -1. You can get more information on indexOf in the MDN Documentation.
That makes your code look like:
var currentURL=location.href;
var str = currentURL;
var badUrls = ["http://web.com/blabla", "http://web.com/bleble"]
if(badUrls.indexOf(str) > -1){
window.location = "http://web.com/ban";
} else {
}
window.location is a browser object, it you want the page to go to http://web.com/ban, you should use
window.location.href = "http://example.com/ban";
However, it looks like you are trying to prevent people from visiting pages using JavaScript. This is extremely insecure, because anyone that lists your code will see which URLs you're trying to protect and immediately request them. If they request those URLs with JavaScript disabled, or using curl, the pages will be delivered.
You should protect the pages with server side configuration. With Apache, you can use the Allow/Deny configuration or RewriteRules.
I was working on how to find a URL's domain, and thanks to my previous question, I came to this answer:
var domain = (location.host)
var arr=domain.split(".")
extension=arr[arr.length-1]
if(extension=="cnn")
alert("true");
However, I have 2 problems:
It works fine untill you come across to a site with extension co.uk.
Is there a way to count . from the start and not from the end?
For example, for the website www.cnn.com, it'd start counting from the www, and not from the com.
Okay, here's the edit to make you understand how it works.
Say, your website is "www.cnn.co.uk". If you understand array, this line would return you the array of 4 elements delimited by '.'
var arr=domain.split(".")
i.e. [www, cnn, co, uk];
Now it's really upto you what element you want out of this array. If you know the element name, and you want to retrieve cnn, you can do
`extension = arr[1];`
You can also iterate over an array to get each element.
extension = arr[0];
it will return you www.
Use this function:
function GetDomainName() {
if (location.host.split('.')[0] == 'www') {
return location.host.split('.')[1];
} else {
return location.host.split('.')[0];
}
}
Call it like this:
var domainName=GetDomainName();
But remember, this will not work in subdomains like
programmers.stackexchange.com
Demo: http://jsfiddle.net/j7VP6/
I have a code, I'll just give a small example below. Though what it does is gets the users name, then checks for other context. Then I check them versus eachother, and my entire script works besides this one point and it's not giving a leeway.
var getName= $('#element').text(),
uName =getName.replace("Welcome ",""),
loggedIn = newMember.replace(membersList,"");
if(loggedIn !== uName)
{
//run other codes
}
Though when I do this it's still running the code. Am I writing the conditional wrong?
From your question title, I assume your concern is that the string comparison of loggedIn !== uName is being impacted by leading and/or trailing spaces on one or the other.
You need to use trim(), and would be wise to validate the presence of the prototype before using it (see this answer for an explanation).
Your code would now be:
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
var getName= $('#element').text(),
uName =getName.replace("Welcome ","").trim(),
loggedIn = newMember.replace(membersList,"").trim();
if(loggedIn !== uName)
{
//run other codes
}
Here's the issue:
I need to check for a parameter in the query. If it's been set, then I need to change it (harder part). If it hasn't been set, I need to set it (easy part)
I was so sure it would be an easy task, but it somehow ended up being a bit more complicated than I thought. Especially for those cases where there are multiple parameters, and the one I'm looking for is in the middle somewhere.
The parameter is "siteLanguage", and is always followed by =xx where xx represents any two characters, like en or es or whatever. So maybe regex is the answer (boy, do I suck at regex)
No frameworks for this one, guys, just plain ol' javascript.
I guess you've figured out how to find all the links.
The standard format of an URL is service://host/path?query
I suggest to cut away the query (just take everything after the first ?) and then split that at & (because that separates parameters).
You'll be left with an array of the form key=value. Split that into an associative array. Now you can work on that array. After you've made your modifications, you need to join the query again and set the href attribute of the link.
This would check all "a href=" throughout the document appending or adjusting the language.
checkhrefs = function(lang){
var links = document.getElementsByTagName("a");
for (var i=0;i<links.length;i++){
if (links[i].href.indexOf("siteLanguage") == -1){
links[i].href += "&siteLanguage="+lang;
} else {
links[i].href = links[i].href.replace(new RegExp("siteLanguage=[a-z][a-z]"),"siteLanguage="+lang);
}
}
}
Ended up just doing a quick hack like so:
function changeLanguage(lang) {
if (location.search.indexOf("siteLanguage") > -1) { //siteLanguage set
location.href = location.search.replace(/siteLanguage=[a-z][a-z]/, "siteLanguage="+lang);
} else if (location.search == "") {
location.href += "?siteLanguage="+lang;
} else {
location.href += "&siteLanguage="+lang;
}
}
Actually pretty happy with a 9-liner function...
I've already looked at this, which was helpful to a point.
Here's the problem. I have a list of users propagated into an element via user click; something like this:
<div id="box">
joe-user
page-joe-user
someone-else
page-someone-else
</div>
On click, I want to make sure that the user has not already been clicked into the div. So, I'm doing something like:
if ( ! $('#box').html().match(rcpt) )
{
update_div();
}
else
{
alert(rcpt+' already exists.');
}
However, with existing lack of interpolation that javascript has for regular expressions, is causing my alert to trigger in the use-case where page-joe-user is selected and then the user selects joe-user, which are clearly not exactly the same.
In Perl I would do something like:
if ( $rcpt =~ /^\Qrcpt\E/ )
{
# code
}
All I want to do is change my match() to be:
if ( ! $('#box').html().match(/^rcpt/) )
{
# code
}
if ( ! $('#box').html().match(rcpt) ) seemed a little promising but it, too, fails. Using new RegExp() also does not work using concatenation of complex RE syntax within the function IE $('#box').html().match(new RegExp('^'+rcpt)). I also tried $('#box').html().match('/^'+rcpt'/'). I can only imagine that I'm missing something. I'm pretty new to javascript.
I don't seem to be able to find anything that really addresses such a use-case, here on this site.
TIA
The match function only works on strings, not jQuery objects.
The best way to do this is to put each username into a separate HTML tag.
For example:
<ul id="users">
<li>joe-user</li>
<li>page-joe-user</li>
<li>someone-else</li>
<li>page-someone-else</li>
</ul>
You can then write the following:
if($('#users li').is(function () { return $(this).text() === rcpt; }))
If you want to do it your way, you should call text() to get the string inside the element. ($('#box').text().match(...))
EDIT: The best way to do this using your HTML would be to split the string.
For example:
var userExists = false;
var users = $('#box').text().split(/\r?\n/);
for(var i = 0; i < users.length; i++) { //IE doesn't have indexOf
if (users[i] == rcpt) {
userExists = true;
break;
}
}
if (userExists) {
//Do something
}
This has the added benefit of not being vulnerable to regex-injection.