Is there a way to use IgnoreCase in Javascript? - javascript

I want to transnlate some words, but i have problems when I write HOUSE in uppercase or mixing. it just work when i write in lowercase
<script>
var translate = prompt("Enter one of the next words:\nhouse\ntable\ndog\ncat");
switch (translate){
case 'house': document.write("casa");
break;
case 'table': document.write("mesa");
break
case 'dog': document.write("perro");
break;
case 'cat': document.write("gato");
break;
default: document.write("Error");
}
</script>

Modified code. (As solution already given in comments. )
<script>
var translate = prompt("Enter one of the next words:\nhouse\ntable\ndog\ncat") || ''; // take '' if user cancel the prompt as it return `null`;
translate = translate.toLowerCase();
switch (translate){
case 'house': document.write("casa");
break;
case 'table': document.write("mesa");
break
case 'dog': document.write("perro");
break;
case 'cat': document.write("gato");
break;
default: document.write("Error");
}
</script>

Use something like toLowercase()
mystr="Hello WORLD !";
document.write(mystr.toLowerCase());
would give "hello world"
apply this to your translate variable
Ref : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase

Related

Is it possible to do something on all switch cases by default without repeating?

Is there a way to repeat a sentence inside of a switch for every case but for default? Without repeating the action inside every case, of course.
I have this:
this.set_estate = function(state){
switch(state){
case 'LOADING':
current= est[state];
break;
case 'WRITING':
current= est[state];
//statements_2
break;
case 'WAITING':
current= est[state];
//statements_3
break;
default:
console.log('tried to set state: '+state);
break;
}
}
And I'd like to know if it could be shifted into something similar to:
this.set_estate = function(state){
switch(state){
case 'LOADING':
case 'WRITING':
case 'WAITING':
current= est[state];
continue;
case 'LOADING':
//statements_1
break;
case 'WRITING':
//statements_2
break;
case 'ESPERANDO':
//statements_3
break;
default:
console.log('tried to set state: '+state);
break;
}
}
Write another switch statement before this to do just the common lines. This would prevent you from writing the code multiple times, if that is your concern.

Switch Statement in Javascript isn't switching

What is wrong with this switch statement? The value I would be selecting this from a select menu with the options/values being 1 or 2. The input field keeps displaying just "1" when it should be "$1500"
$('[name="costfield"]').change(function(){
var cost = this.value;
switch(cost){
case 1:
cost = "$1500";
break;
case 2:
cost = "$2500";
break;
}
$('#exampleInputEstimate1').val(cost);
});
Use strings in the case statement - https://jsfiddle.net/3ujg7kr8/
$('[name="costfield"]').change(function(){
var cost = this.value;
switch(cost){
case '1':
cost = "$1500";
break;
case '2':
cost = "$2500";
break;
}
$('#exampleInputEstimate1').val(cost);
});
The switch statement use strict comparison according to MDN.
For appropriate use I suggest using strings in this case.
When you retrieve the value from the input, you get strings, i.e. '1' or '2'.
Therefore you have to parse it as an integer or a float:
Replace:
var cost = this.value;
with:
var cost = parseInt(this.value, 10);
The other solution would be to enumerate strings in the switch/case, as it was already pointed:
switch(cost){
case '1':
cost = "$1500";
break;
case '2':
cost = "$2500";
break;
default:
break;
}
By the way take the habit to write a default case in switch statements

Switch with random not working

This is my current jScript code:
(modified STILL doesn't work)
function changeBG(){
document.getElementById('imgbox').src = switch(eval(rand())){
case 1: "img/img3.jpg";
break;
case 2: "img/img2.jpg";
break;
case 3: "img/img3.jpg";
break;
case 4: "img/img4.jpg";
break;
case 5: "img/img5.jpg";
break;
default: "img/background.jpg";
break;
}
}
function rand(){
return (Math.ceil((Math.random()*10)/2));
}
my HTML:
<input id="BGchange" type="button" onclick="changeBG()" value=">"/>
If I do something like this:
document.getElementById('imgbox').src = "img/img1.jpg";
It just works: I click on my button, the image changes, no problem. Fact is I want the image to change to a random one between 5 each time the button is clicked; to do this I wanted to use a switch that works with a random choice inside it.
What is wrong with my coding?! :( (I cant use jQuery or anything, just pure javascript, html and css, thats what the professor said at least)
Thank you <3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
The switch-statement "executes" your Strings ("img/imgX.jpg") instead of returning them, so you may want put the switch in a function and then do
case 1: return "img/img3.jpg";
...
and keep in mind that each case of a switch statement must be terminated with break, otherwise the following case-Blocks will be executed as well!
Your function return an integer, while your switch case is looking for a string.
Remove quotes from the switch cases and everything should work.
function changeBG(){
document.getElementById('imgbox').src = switch(rand()){
case 1: "img/img3.jpg";
break;
case 2: "img/img2.jpg";
break;
case 3: "img/img3.jpg";
break;
case 4: "img/img4.jpg";
break;
case 5: "img/img5.jpg";
break;
default: "img/background.jpg";
}
}

windows.location.pathname not working

I'm having issue with one of my cases not working. They all work except for one, which actually has queries in the URL, but they are always the same. The query URL looks like this: http://mywebsite.com/search/?q=label:Web-Design|label:Graphic-Design|label:Identity-Design|label:Brand-Design
It's not working and I'm wondering if windows.location supports queries in URL. It seems to me it wouldn't matter, but either way I cannot get this working.
I'm 100% positive that is the correct pathname, as I copied & pasted it, only to remove the domain just like the rest.
This is what I am using:
<script type='text/javascript'>
$(document).ready(function(){
switch (window.location.pathname) {
default:
$('.nav-blog').addClass('current');
break;
case '/p/about.html':
$('.nav-about').addClass('current');
break;
case '/':
$('.nav-home').addClass('current');
break;
case '/search/blog':
$('.nav-blog').addClass('current');
break;
case '/p/forums.html':
$('.nav-forums').addClass('current');
break;
case '/search/?q=label:Web-Design|label:Graphic-Design|label:Identity-Design|label:Brand-Design':
$('.nav-design').addClass('current');
break;
case '/p/photography.html':
$('.nav-photography').addClass('current');
break;
case '/p/hosting.html':
$('.nav-hosting').addClass('current');
break;
}
});
</script>
Change the variable in the switch to include the query string
$(document).ready(function(){
switch (window.location.pathname + window.location.search) {
default:
$('.nav-blog').addClass('current');
break;
case '/p/about.html':
$('.nav-about').addClass('current');
break;
case '/':
$('.nav-home').addClass('current');
break;
case '/search/blog':
$('.nav-blog').addClass('current');
break;
case '/p/forums.html':
$('.nav-forums').addClass('current');
break;
case '/search/?q=label:Web-Design|label:Graphic-Design|label:Identity-Design|label:Brand-Design':
$('.nav-design').addClass('current');
break;
case '/p/photography.html':
$('.nav-photography').addClass('current');
break;
case '/p/hosting.html':
$('.nav-hosting').addClass('current');
break;
}
});
However this will not match against the other cases if they have querystrings on the end, also currently your switch statement is case sensitive, you should probably toUpperCase() or toLowerCase() your switch.
This should fix most of your issues:
$(document).ready(function(){
var path = window.location.pathname.toLowerCase();
if(path == '/search/')
{
if(window.location.search.toLowerCase() == '?q=label:web-design|label:graphic-design|label:identity-design|label:brand-design')
$('.nav-design').addClass('current');
else
$('.nav-blog').addClass('current');
}
else
{
switch (path) {
default:
$('.nav-blog').addClass('current');
break;
case '/p/about.html':
$('.nav-about').addClass('current');
break;
case '/':
$('.nav-home').addClass('current');
break;
case '/search/blog':
$('.nav-blog').addClass('current');
break;
case '/p/forums.html':
$('.nav-forums').addClass('current');
break;
case '/p/photography.html':
$('.nav-photography').addClass('current');
break;
case '/p/hosting.html':
$('.nav-hosting').addClass('current');
break;
}
}
});
You should do even more sanitization of your inputs (window.location.path, window.location.search) than I am here like trimming them (removing leading and trailing whitespace) and removing the leading and trailing slashes etc.
Also what happens if for some reason your query string values are in a different order?
Things like this can happen for instance someone emails a link and it has a extra space at the end or somewhere in the query string, when the recipient clicks the link they may go to the right page but your switch will hit the default.

Switch statement for multiple cases in JavaScript

I need multiple cases in switch statement in JavaScript, Something like:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the DRY concept.
Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
}
This works in regular JavaScript:
function theTest(val) {
var answer = "";
switch( val ) {
case 1: case 2: case 3:
answer = "Low";
break;
case 4: case 5: case 6:
answer = "Mid";
break;
case 7: case 8: case 9:
answer = "High";
break;
default:
answer = "Massive or Tiny?";
}
return answer;
}
theTest(9);
Here's different approach avoiding the switch statement altogether:
var cases = {
afshin: function() { alert('hey'); },
_default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;
cases[ varName ] ? cases[ varName ]() : cases._default();
In Javascript to assign multiple cases in a switch, we have to define different case without break inbetween like given below:
<script>
function checkHere(varName){
switch (varName)
{
case "saeed":
case "larry":
case "afshin":
alert('Hey');
break;
case "ss":
alert('ss');
break;
default:
alert('Default case');
break;
}
}
</script>
Please see example click on link
I like this for clarity and a DRY syntax.
varName = "larry";
switch (true)
{
case ["afshin", "saeed", "larry"].includes(varName) :
alert('Hey');
break;
default:
alert('Default case');
}
If you're using ES6, you can do this:
if (['afshin', 'saeed', 'larry'].includes(varName)) {
alert('Hey');
} else {
alert('Default case');
}
Or for earlier versions of JavaScript, you can do this:
if (['afshin', 'saeed', 'larry'].indexOf(varName) !== -1) {
alert('Hey');
} else {
alert('Default case');
}
Note that includes won't work in some browser including older IE versions, but you could patch things up fairly easily. See the question determine if string is in list in javascript for more information.
My situation was something akin to:
switch (text) {
case SOME_CONSTANT || ANOTHER_CONSTANT:
console.log('Case 1 entered');
break;
case THIRD_CONSTANT || FINAL_CONSTANT:
console.log('Case 2 entered');
break;
default:
console.log('Default entered');
}
The default case always entered. If you're running into a similar multi-case switch statement issue, you're looking for this:
switch (text) {
case SOME_CONSTANT:
case ANOTHER_CONSTANT:
console.log('Case 1 entered');
break;
case THIRD_CONSTANT:
case FINAL_CONSTANT:
console.log('Case 2 entered');
break;
default:
console.log('Default entered');
}
Adding and clarifying Stefano's answer, you can use expressions to dynamically set the values for the conditions in switch, e.g.:
var i = 3
switch (i) {
case ((i>=0 && i<=5) ? i : -1):
console.log('0-5');
break;
case 6: console.log('6');
}
So in your problem, you could do something like:
var varName = "afshin"
switch (varName) {
case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
console.log("hey");
break;
default:
console.log('Default case');
}
Although it is so much DRY...
In Node.js it appears that you are allowed to do this:
data = "10";
switch(data){
case "1": case "2": case "3": // Put multiple cases on the same
// line to save vertical space.
console.log("small");
break;
case "10": case "11": case "12":
console.log("large");
break;
default:
console.log("strange");
break;
}
This makes for much more compact code in some cases.
I use it like this:
switch (true){
case /Pressure/.test(sensor):
{
console.log('Its pressure!');
break;
}
case /Temperature/.test(sensor):
{
console.log('Its temperature!');
break;
}
}
Some interesting methods. For me the best way to solve is using .find.
You can give an indication of what the multiple cases are by using a suitable name inside your find function.
switch (varName)
{
case ["afshin", "saeed", "larry"].find(firstName => firstName === varName):
alert('Hey');
break;
default:
alert('Default case');
break;
}
Other answers are more suitable for the given example but if you have multiple cases to me this is the best way.
It depends. Switch evaluates once and only once. Upon a match, all subsequent case statements until 'break' fire no matter what the case says.
var onlyMen = true;
var onlyWomen = false;
var onlyAdults = false;
(function(){
switch (true){
case onlyMen:
console.log ('onlymen');
case onlyWomen:
console.log ('onlyWomen');
case onlyAdults:
console.log ('onlyAdults');
break;
default:
console.log('default');
}
})(); // returns onlymen onlywomen onlyadults
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
You can use the 'in' operator...
It relies on the object/hash invocation, so it's as fast as JavaScript can be.
// Assuming you have defined functions f(), g(a) and h(a,b)
// somewhere in your code,
// you can define them inside the object, but...
// the code becomes hard to read. I prefer it this way.
o = { f1:f, f2:g, f3:h };
// If you use "STATIC" code can do:
o['f3']( p1, p2 )
// If your code is someway "DYNAMIC", to prevent false invocations
// m brings the function/method to be invoked (f1, f2, f3)
// and you can rely on arguments[] to solve any parameter problems.
if ( m in o ) o[m]()
You can do this:
alert([
"afshin",
"saeed",
"larry",
"sasha",
"boby",
"jhon",
"anna",
// ...
].includes(varName)? 'Hey' : 'Default case')
or just a single line of code:
alert(["afshin", "saeed", "larry",...].includes(varName)? 'Hey' : 'Default case')
a little improvement from ErikE's answer
I can see there are lots of good answers here, but what happens if we need to check more than 10 cases? Here is my own approach:
function isAccessible(varName){
let accessDenied = ['Liam', 'Noah', 'William', 'James', 'Logan', 'Benjamin',
'Mason', 'Elijah', 'Oliver', 'Jacob', 'Daniel', 'Lucas'];
switch (varName) {
case (accessDenied.includes(varName) ? varName : null):
return 'Access Denied!';
default:
return 'Access Allowed.';
}
}
console.log(isAccessible('Liam'));
The problem with the above approaches, is that you have to repeat the several cases every time you call the function which has the switch. A more robust solution is to have a map or a dictionary.
Here is an example:
// The Map, divided by concepts
var dictionary = {
timePeriod: {
'month': [1, 'monthly', 'mensal', 'mês'],
'twoMonths': [2, 'two months', '2 months', 'bimestral', 'bimestre'],
'trimester': [3, 'trimesterly', 'quarterly', 'trimestral'],
'semester': [4, 'semesterly', 'semestral', 'halfyearly'],
'year': [5, 'yearly', 'annual', 'ano']
},
distance: {
'km': [1, 'kms', 'kilometre', 'kilometers', 'kilometres'],
'mile': [2, 'mi', 'miles'],
'nordicMile': [3, 'Nordic mile', 'mil (10 km)', 'Scandinavian mile']
},
fuelAmount: {
'ltr': [1, 'l', 'litre', 'Litre', 'liter', 'Liter'],
'gal (imp)': [2, 'imp gallon', 'imperial gal', 'gal (UK)'],
'gal (US)': [3, 'US gallon', 'US gal'],
'kWh': [4, 'KWH']
}
};
// This function maps every input to a certain defined value
function mapUnit (concept, value) {
for (var key in dictionary[concept]) {
if (key === value ||
dictionary[concept][key].indexOf(value) !== -1) {
return key
}
}
throw Error('Uknown "'+value+'" for "'+concept+'"')
}
// You would use it simply like this
mapUnit("fuelAmount", "ltr") // => ltr
mapUnit("fuelAmount", "US gal") // => gal (US)
mapUnit("fuelAmount", 3) // => gal (US)
mapUnit("distance", "kilometre") // => km
// Now you can use the switch statement safely without the need
// to repeat the combinations every time you call the switch
var foo = 'monthly'
switch (mapUnit ('timePeriod', foo)) {
case 'month':
console.log('month')
break
case 'twoMonths':
console.log('twoMonths')
break
case 'trimester':
console.log('trimester')
break
case 'semester':
console.log('semester')
break
case 'year':
console.log('year')
break
default:
throw Error('error')
}
One of the possible solutions is:
const names = {
afshin: 'afshin',
saeed: 'saeed',
larry: 'larry'
};
switch (varName) {
case names[varName]: {
alert('Hey');
break;
}
default: {
alert('Default case');
break;
}
}
If your case conditions are complex, many case value matches, or dynamic value match required, then it may be best to move that case matching logic to handler child functions.
In your case, if say you had thousands of usernames to match against for a security permissions check for example, this method is cleaner option, more extensible, exposing the high level multi-way branch logic without getting swamped in a long list of case statements.
switch (varName)
{
case checkPatternAdministrator(varName):
alert('Hey');
break;
case checkPatternUserTypeA(varName):
alert('Hey2');
break;
case checkPatternUserTypeB(varName):
alert('Hey3');
break;
default:
alert('Default case');
break;
}
function checkPatternAdministrator(varName) {
// Logic to check Names against list, account permissions etc.
// return the varName if a match is found, or blank string if not
var matchedAdministratorName = varName;
return matchedAdministratorName;
}
Here is one more easy-to-use switch case statement. which can fulfill your requirement. We can use the find method in the switch statement to get the desire output.
switch(varname){
case["afshin","saeed","larry"].find(name => name === varname):
alert("Hey")
break;
default:
alert('Default case');
break;
}
The switch statement is used to select one of many code blocks to execute based on a condition
the value in the switch expression is compared to the different values provided
if there is a match the code block related to it will be executed
if there is no match the default block is executed
syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
NOTE:
It must be noted that if the break statement is omitted then the next block will be executed as well even if they does not match with switch expression. So don't forget to add the break statement at the end of each code block if you don't want to get the specified behaviour
A practical example:
the following code returns the current day of the week in strings based on an integer (provided by 'new Date().getDay()')
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
the code samples were taken from W3Schools
Another way of doing multiple cases in a switch statement, when inside a function:
function name(varName){
switch (varName) {
case 'afshin':
case 'saeed':
case 'larry':
return 'Hey';
default:
return 'Default case';
}
}
console.log(name('afshin')); // Hey
Cleaner way to handle that
if (["triangle", "circle", "rectangle"].indexOf(base.type) > -1)
{
//Do something
}else if (["areaMap", "irregular", "oval"].indexOf(base.type) > -1)
{
//Do another thing
}
You can do that for multiple values with the same result
Just change the switch condition approach:
switch (true) {
case (function(){ return true; })():
alert('true');
break;
case (function(){ return false; })():
alert('false');
break;
default:
alert('default');
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example1</title>
<link rel="stylesheet" href="css/style.css" >
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
function display_case(){
var num = document.getElementById('number').value;
switch(num){
case (num = "1"):
document.getElementById("result").innerHTML = "You select day Sunday";
break;
case (num = "2"):
document.getElementById("result").innerHTML = "You select day Monday";
break;
case (num = "3"):
document.getElementById("result").innerHTML = "You select day Tuesday";
break;
case (num = "4"):
document.getElementById("result").innerHTML = "You select day Wednesday";
break;
case (num = "5"):
document.getElementById("result").innerHTML = "You select day Thusday";
break;
case (num = "6"):
document.getElementById("result").innerHTML = "You select day Friday";
break;
case (num = "7"):
document.getElementById("result").innerHTML = "You select day Saturday";
break;
default:
document.getElementById("result").innerHTML = "You select day Invalid Weekday";
break
}
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<h2> Switch Case Example </h2>
<p>Enter a Number Between 1 to 7</p>
<input type="text" id="number" />
<button onclick="display_case();">Check</button><br />
<div id="result"><b></b></div>
</center>
</center>
</body>
You could write it like this:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
For me this is the simplest way:
switch (["afshin","saeed","larry"].includes(varName) ? 1 : 2) {
case 1:
alert('Hey');
break;
default:
alert('Default case');
break;
}

Categories