i am currently working on a simple ipad webapp testpiece and got stuck in a simple switch statement that doesn´t work somehow;
i want to format elements according to javascripts window.location string. This might be embarassing simple to fix; but i somehow don´t get it:
Or is there something special about the window.location?
$(document).ready(function() {
path_c = window.location;
switch (path_c){
case "http://192.168.1.37/ryba_testground/":
$('#menu-item-22').addClass('current_page_item');
alert(path_c);
break;
case "http://192.168.1.37/ryba_testground/?page_id=7":
$('#menu-item-21').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=9":
$('#menu-item-20').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=11":
$('#menu-item-19').addClass('current_page_item');
break;
}
});
THX!
Or is there something special about the window.location?
It's a host object, which sometimes act unpredictable. At least, it is an object which evaluates to the href when casted to a string - yet that does not happen when comparing with the switch-cases. Use
var path_c = window.location.href;
window.location returns a Location object, which contains information about the URL of the document and provides methods for changing that URL. So change it to:
var path_c = window.location.href;
I think you want the href property of the window.location object.
path_c = window.location.href;
Full Script
$(document).ready(function() {
path_c = window.location.href;
switch (path_c){
case "http://192.168.1.37/ryba_testground/":
$('#menu-item-22').addClass('current_page_item');
alert(path_c);
break;
case "http://192.168.1.37/ryba_testground/?page_id=7":
$('#menu-item-21').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=9":
$('#menu-item-20').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=11":
$('#menu-item-19').addClass('current_page_item');
break;
}
});
Example: http://jsfiddle.net/9vjY9/
The code seems ok. Try to alert (window.location.href) or console.log(window.location.href), then you can check exactly what does window.location.href gets for each page you test. This might reveal the problem.
You can use window.location.toString() or window.location.href, you even can avoid using switch, with a object map and regular expression to filter your target in url:
var page_idMap = {
'7': '#menu-item-21',
'9': '#menu-item-20',
'11': '#menu-item-19'
}
var id = window.location.href.match(/page_id[=]([0-9]+)/i);
if (!id || !page_idMap(id[1])) {
$('#menu-item-22').addClass('current_page_item');
} else {
$(page_idMap[id[1]]).addClass('current_page_item');
}
Related
I have a js array like that:
let data = [{status:"stay",points:[1,2,3,4,5]}, {status:"move",points:[1,2,3,4,5]},{status:"stay",points:[1,2,3,4,5]}]
And I want to do some pattern match, here is my code:
switch (data){
case [{status:"move",_},{status:"stay",_},{status:"move",_}]:
console.log("successfully!")
}
And I don't care the points array, but in js the placeholder "_" not exist, actually I know other method to do this, but if we just use switch-case, can it be solved?
I am a newbie of js, anynoe knows how to do it?
If I understand what you're trying to do correctly, you might try reducing your array to a string, and then use that string in the switch statement. Something like this:
var actionString = ""
data.forEach(function(datum) {
actionString += datum.status + ' ';
});
// Remove extra space at the end
actionString.trim();
console.log(actionString); // "move stay move"
Then your switch statement would be:
switch(actionString) {
case "move stay move":
console.log('success!');
break;
case "stay move stay":
console.log('failure?');
break;
/* etc */
}
Try
switch (data.status){
case "stay":
case "move":
console.log("successfully!")
break;
}
Documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Not sure why the code below is not working. It should take in a string and convert a G to a C and an A to a T and vice versa. However, it collects the input string but doesn't provide any output i.e. the alert just says "here is your reverse complement DNA"
var dnaSequence = prompt("Enter your DNA sequence here", "");
var newSequence = reverseComplement(dnaSequence);
alert("here is your reverse complemented DNA: " + newSequence);
function reverseComplement(dnaString) {
var reverseC = [];
var dnaArr = dnaString.split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.reverse().join('');
}
It should take in a string and convert a G to a C and an A to a T and vice versa.
Then you don't need the reverse(), because you are pushing in order.
Also, Make sure that you are entering uppercase letters into the prompt.
Else, you can force the uppercase.
This is the code with the two fixes:
function reverseComplement(dnaString) {
var reverseC = [];
var dnaArr = dnaString.toUpperCase().split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.join('');
}
var dnaSequence = prompt("Enter your DNA sequence here", "");
var newSequence = reverseComplement(dnaSequence);
alert("here is your reverse complemented DNA: " + newSequence);
The main lesson you need here is how to test and debug your JavaScript code.
First, get familiar with the JavaScript debugger in your browser. Instead of wondering why your code doesn't work, you can see directly what it is doing. Every modern browser has built-in JavaScript debugging tools; for example here is an introduction to the Chrome DevTools.
Second, when you are testing a function like this, don't use prompt() or alert(). Instead, provide a hard coded input string and use console.log() to display the output in the JavaScript debug console. This way you can run the same test case repeatedly. After you get one test case to work, you can add others.
There are several JavaScript testing frameworks if you want to get fancy, but to start with, simply using a hard coded input and console.log() output plus inspection in the JavaScript debugger is fine.
To make it easy to debug a function when you first write it, add a debugger; statement at the beginning. Then it will stop in the debugger and you can single-step through the code to see which parts of your function actually get executed and what all your variable values are at each step of the way.
For example (since it sounds like you were mistakenly testing with lowercase input), you might do this:
var dnaSequence = 'actg';
var newSequence = reverseComplement(dnaSequence);
console.log(newSequence);
function reverseComplement(dnaString) {
debugger;
var reverseC = [];
var dnaArr = dnaString.split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.reverse().join('');
}
Now, if you have the DevTools open, it will stop in the debugger at the first line of your function. You can single-step through the function to see which of the case statements it actually goes to, and you will see that it doesn't go to any of them. You can also look at the value of dnaArr[i] and see whether it matches any of the case values.
i need to identify the data/text being submitted from <input> if it contains any of the following. youtube, vimeo,normal website, jpg/png, plain text
if a youtube link is found {
//do something
} else if a vimeo link is found {
//do something
} else if a normal website is found {
//do something
} else if a (jpg/png) is found {
//do something
} else just a text {
} //do something
as of the moment is my syntax. the youtube & vimeo regex format were taken from other posts. but im not sure how to create the proper regex for the others.
ive tried some regex generator but its so complicated to use
im also interested to know if this is the proper way of executing multiple conditional statement.
$(function() {
$(document).on('click','.submit', function () {
var data = $('#input').val();
var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var vimeo = /^(http\:\/\/|https\:\/\/)?(www\.)?(vimeo\.com\/)([0-9]+)$/;
if (data.match(youtube)) {
alert("utube");
}
else if (data.match(vimeo)) {
alert("vimeo");
}
else if ...
});
});
There is a million different ways to do this.
The other regex you need are roughly bellow. Also it will save you a bit of a headache if you lowercase your data
var data = $("#input").val.toLowerCase();
Web url
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/
PNG / JPG is at end of the string
/(png|jpg|jpeg)$/
Plain text i guese would be what ever is left
The most efficient way is also to use a switch statement not a big if else
like this http://www.w3schools.com/js/js_switch.asp
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
I would suggest using a switch statement when you have multiple regex conditions to check for:
var data = $('#input').val();
var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var vimeo = /^(http\:\/\/|https\:\/\/)?(www\.)?(vimeo\.com\/)([0-9]+)$/;
var normalWebsite = /^(?:ftp|http|https):\/\/(?:[\w\.\-\+]+:{0,1}[\w\.\-\+]*#)?(?:[a-z0-9\-\.]+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:\.\?\+=&%#!\-\/\(\)]+)|\?(?:[\w#!:\.\?\+=&%#!\-\/\(\)]+))?$/;
var image = /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/;
switch (true) {
case youtube.test(data):
alert('youtube');
break;
case vimeo.test(data):
alert('vimeo');
break;
case normalWebsite.test(data):
alert('normal website');
break;
case image.test(data):
alert('image');
break;
default:
// Here we are assuming anything that doesn't match the above is plain text.
// You will need an additional regex if you want to make sure this doesn't contain html or code.
alert('Plain text');
break;
}
I need to check whether a URL is an image.
The answer here
/(jpg|gif|png)$/.test(...
raises a false positive in my (special) case when there's an extension in a non-image URL
http://www.example.com/jpg/bpgpage/
(PS: can't use jquery, only javascript/regex)
Provided that the uri ends with the extension, this should work every time.
Code:
var isUriImage = function(uri) {
//make sure we remove any nasty GET params
uri = uri.split('?')[0];
//moving on, split the uri into parts that had dots before them
var parts = uri.split('.');
//get the last part ( should be the extension )
var extension = parts[parts.length-1];
//define some image types to test against
var imageTypes = ['jpg','jpeg','tiff','png','gif','bmp'];
//check if the extension matches anything in the list.
if(imageTypes.indexOf(extension) !== -1) {
return true;
}
}
Example:
http://jsfiddle.net/fMCFB/1/
Maybe you can add a dot . before the regular expression, as such:
/\.(jpg|gif|png)$/.test( ..
That will try to match .jpg, .gif and .png in URLs.
The regular expression you mentioned though, does try to search for jpg, gif and png only at the end of the URL, so I'm not sure how it matched http://www.example.com/jpg/bpgpage/.
If you ommit the dot . though, it will still match http://www.example.com/jpg
you can verify in the content Type header here's a function example:
async function verifyUrlImage(url){
try{
let resp= $.ajax(url);
await resp;
let headers=resp.getAllResponseHeaders().split(/\n/g);
for(let i=0;i<=headers.length;i++){
let hd=headers[i].split(': ')
if (hd[0]=='content-type' && hd[1].indexOf('image')==0)
return true;
}
}
catch{}
return false;
}
So this will look if content-type starts with image then the link is an image acording this image types:
https://www.iana.org/assignments/media-types/media-types.xhtml#image
you can test it:
let isImage = await verifyUrlImage('https://www.gravatar.com/avatar/332cf4cffa6c5161c026485b98655079?s=48&d=identicon&r=PG');
Here's what I would do, where "str" is the string you're matching:
return (str.match(/\.(jpg|gif|png)$/)!= null);
// function for check the type of any source
function checkExtension(file) {
var extension = file.substr((file.lastIndexOf('.') + 1));
switch (extension) {
case 'jpg':
case 'png':
case 'gif':
return "img" // There's was a typo in the example where
break; // the alert ended with pdf instead of gif.
case 'mp4':
case 'mp3':
case 'ogg':
return "video"
break;
case 'html':
return "html"
break;
}
};
var ex = checkExtension("if-a-link-is-an-image.png")
console.log(ex)
Why not pull the last three characters using substr?
url.substr(url.length-3, 3);
I have been looking in both Jmeter and Javascript forums and can't figure out why this case statement is always matching to the default and I wondered if it was a Jmeter condition that I was missing.
I don't think it is a data problem. The URLTYPE_ variable is being set by a CSV input. Here are two lines from it.
Thumbnail,XXXXXX/XXXXXX,
Caption,XXXXXXXX/XXXXXX,
Code Snippet :
var t = vars.get("URLTYPE_");
log.info("starting");
log.info(t);
switch (t)
{
case "Thumbnail":
vars.put("CGIURL", "thumbres");
vars.put("LBURL", "thumb");
log.info("thumb");
break;
case "Caption":
vars.put("CGIURL", "capt");
vars.put("LBURL", "c");
log.info("c");
break;
default:
vars.put("CGIURL", "thumbres");
vars.put("LBURL", "thumb");
log.info("Default");
break;
}
log.info("stopping");
Try using if clauses instead of case with == comparison.