sorry I'm french and I speak just few word in english.
I have a question maybe stupid :
Original code :var test = {
commandChar : "!",
};
for (i = 0; i < commands.length; i++) {
if (commands[i].hasOwnProperty('alt')) {
for (j = 0; j < commands[i].alt.length; j++) {
if ((index = text.toLowerCase().search(new RegExp("^\\" + test.commandChar + commands[i].alt[j].toLowerCase() + "\\b"))) >= 0) {
break;
}
}
}
if (index < 0) {
index = text.toLowerCase().search("^\\" + "[" + test.commandChar + ",##]" + commands[i].name.toLowerCase() + "\\b");
}
if (index > -1) {
var command = text.slice(index).split(" ");
if (!(commands[i].op || commands[i].elevated) || host || mod || authorised) {
if (!(commands[i].mod) || host || mod) {
commands[i].command(command, user);
}
}
else {
//sendChat("You have to be authorised to use " + commands[i].name + ".");
}
break;
}
}
This is an little bot, example.
If commandChar : "!". !help work but /help dont work.
I want just use this commandChar with many symbole
like
commandChar : "!", "/";
for use !help and /help
I think it should or array or regexpr
Sorry if I did not express myself properly it's complicated, thanks
There's many ways to do it but here's a quick one:
function isValidCommandChar(str) {
return "!/.".indexOf(str.charAt(0)) > -1;
}
isValidCommandChar("!help"); // true
isValidCommandChar("#help"); // false
isValidCommandChar("/help"); // true
isValidCommandChar(".help"); // true
Related
I am trying to write a function that will validate that all entries within the commas are numberic and display "?" if they are not. for example: user enters 2,3,5b,c7 the output that I am getting is BCE? instead of BC?? This is the decode function that I am trying to validate in:
function fnDecode() {
var msg = $("textin").value;
if(msg === "") {
$("textin_span").innerHTML = "* Please enter a value to decode
*";
$("textin").focus();
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(","); //split method separates by delimiter
var outstr = ""; //out string
for (var i=0; i<nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) { //if isNaN true, print ?
outstr += "?";
} else if (isNallN(nums[i])) { //THIS IS WHERE THE FN GOES
outstr += "?";
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 >26) {
outstr += "?";
}else {
outstr += String.fromCharCode(n2+64);
}
}
$("textout").value = outstr;
}
function isNallN(s) {
}
I corrected your fnDecode function.
You don't need multiple if to check for isNaN, !isNaN('5') will work as well as !isNaN(5). Check this Javascript Equality Table for more information.
Here, I adapted the function for it to work with a String given in
parameter and to return the wanted String.
function fnDecode(msg) {
var nums = msg.split(",");
var outstr = "";
for (num of nums) {
if (isNaN(num)) outstr += "?"; //isNaN works on "5" and 5
else if (+num === 0) outstr += " "; //We use +num to parse the String to an int
else if (+num < 1 || +num > 26) outstr += "?";
else outstr += String.fromCharCode(+num + 64);
}
return outstr;
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a shorter ES6 version :
function fnDecode(msg) {
return msg.split(',').map( num => isNaN(num) || (+num < 1 || +num > 26) ? '?' : +num == 0 ? ' ' : String.fromCharCode(+num + 64)).join('');
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
Please see my js validation function below.
function validate_submit(PassForm) {
var bGo = false;
var rankcount = document.getElementById('rankCount').value;
var j = 0;
var iRankcount0 = document.getElementById('indRankcount0').value;
var iRankcount1 = document.getElementById('indRankcount1').value;
var iRankcount2 = document.getElementById('indRankcount2').value;
var ijs = 0;
var itemp = ijs;
for (i = 0; i < rankcount; i++) {
alert("begin i = " + i);
if (i == 0) {
indRankcount = iRankcount0;
}
else if (i == 1) {
alert('indRankcount: ' + indRankcount);
indRankcount = iRankcount1;
alert('iRankcount1: ' + iRankcount1);
alert('indRankcount: ' + indRankcount);
}
else if (i == 2) {
indRankcount = iRankcount2;
}
alert('before sec loop indRank: ' + indRankcount);
alert('before sec loop itemp: ' + itemp);
for (k = itemp; k < indRankcount; k++) {
alert('in check bGo');
if (document.getElementById("selectedScore" + i + k).checked) {
bGo = true;
j++;
} //if
} //for indRankcount - k loop
if (bGo) {
if (i == 0) {
par = (Math.ceil(indRankcount / 4));
}
else if (i == 1) {
par = (Math.ceil((iRankcount1 - iRankcount0) / 4));
alert('1: ' + par);
}
else if (i == 2) {
par = (Math.ceil((indRankcount2 - iRankcount1) / 4));
}
if (j == par) {
j = 0;
bGo = false;
itemp = indRankcount;
alert("itemp = " + itemp);
continue;
}
else {
alert('25% criteria not met.');
return false;
}
}
else { //else to check bGo
alert('Atleast one box need to be selected.');
return false;
}
j = 0;
bGo = false;
itemp = indRankcount;
alert("loop ends: i =" + i);
} //for rankcount - i loop
res = window.confirm('Are you sure you want to proceed with the selection?');
if (res) {
return true;
}
else {
return false;
}
} //end of validate
Problem is when i=0, it executes fine. But when i=1, second loop (K) doesn't execute(we switched the variable to constant- it works for either itemp or indRankcount.Just one number did it.) It totally skips. Help please! Thank you!
After the inner loop (which uses "k"), there is a "itemp = indRankcount;" line. I guess this cause the issue.
On the first run the "itemp" is 0 so the inner loop step in, but on the second run this value more or equal with the "indRankcount", because you call the code before.
What values are stored in "iRankcount0", "iRankcount1" and "iRankcount2"?
Try to print the "itemp" and "indRankcount" values before the 2. loop.
Updated, try this before the k loop, it will show why the k not starts on the 2. execution.
Console.log(i + "loop:: " + itemp + " val (k first val), " + " indRankcount " + val (k end val));
Someone please help what is wrong in the following code. It is saying "Unexpected token else" while validating javascript code on Java Validate website - esprima.org
`
function add1()
{
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1 ; i<=size ; i += 1 )
{
for (j = 1 ; j<=size ; j += 1)
{
If (i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
`
In Javascript there is no If statement. Javascript is a case-sensitive language Write it in the lower case - if. And also refactor your code, you have some unused variables.
The problem is that If should be lowercase.
The code should be like this:
function add1() {
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1; i <= size; i += 1) {
for (j = 1; j <= size; j += 1) {
if(i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
function add1()
{
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1 ; i<=size ; i += 1 )
{
for (j = 1 ; j<=size ; j += 1)
{
if (i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
working code,you forget make your if in lowercase
I'm trying to fix some errors according to JSLint and there are some errors I can't get rid of:
line 46 character 13
Missing 'new'.
SortPosts(categories[categoryNumber].textContent);
line 65 character 16
Unexpected '('.
if (typeof (Storage) !== "undefined") {
line 65 character 9Unexpected 'typeof'. Use '===' to compare directly with undefined.
if (typeof (Storage) !== "undefined") {
This is my code:
window.onload = function () {
"use strict";
var categories,
value,
i,
j,
article,
li,
postsAvailable = false;
function removeElementsByClass() {
var elements = document.getElementsByClassName("forumPost");
while (elements.length > 0) {
elements[0].parentNode.removeChild(elements[0]);
}
}
function addRow(input) {
article = document.createElement('article');
article.className = 'forumPost';
article.innerHTML = "<div id='imageDiv'><img src='" + input.avatar + "' alt='Avatar'id='imageHTML'/><div id='personDiv'> " + input.firstName + " " + input.lastName + " (" + input.age + ") </div><div id='workDiv'>" + input.work + " </div></div><div id='headerDiv'>" + input.firstName + " schreef om <div id='dateDiv'>" + input.date + "</div></div></br><div id='postDiv'>" + input.post + "</div></article>";
document.getElementById('content').appendChild(article);
}
function SortPosts(category) {
if (localStorage.getItem(category) === "") {
alert("No posts found!");
} else {
removeElementsByClass();
if (category !== "Algemeen") {
value = JSON.parse(localStorage.getItem(category));
for (i = 0; i < value.length; ++i) {
addRow(value[i]);
}
} else {
for (i = 0; i < localStorage.length; ++i) {
if (localStorage.getItem(localStorage.key(i)) !== "") {
value = JSON.parse(localStorage.getItem(localStorage.key(i)));
for (j = 0; j < value.length; ++j) {
addRow(value[j]);
}
}
}
}
}
}
function getPostSorter(categoryNumber) {
return function () {
SortPosts(categories[categoryNumber].textContent);
};
}
document.getElementById("newCategoryButton").onclick = function () {
var input = document.getElementById("newCategoryInput").value;
if (input !== "") {
if (localStorage.getItem(input) !== null) {
alert("Categorie bestaat al!");
} else {
li = document.createElement('li');
li.innerHTML = "<a href='#'>" + input + "</a></li>";
localStorage.setItem(input, "");
document.getElementById("categories").appendChild(li);
}
} else {
alert("Uw invoer mag niet leeg zijn!");
}
document.getElementById("newCategoryInput").value = "";
};
if (typeof (Storage) !== "undefined") {
for (i = 0; i < localStorage.length; ++i) {
if (localStorage.getItem(localStorage.key(i)) !== "") {
postsAvailable = true;
break;
}
}
if (postsAvailable === false) {
article = document.createElement('article');
article.className = 'infobox';
article.innerHTML = "<header><h2>Geen posts gevonden!</h2></header><section><p>Ga naar het forum toe om een onderwerp toe te voegen</p></section></article>";
document.getElementById('content').appendChild(article);
} else {
for (i = 0; i < localStorage.length; ++i) {
if (localStorage.getItem(localStorage.key(i)) !== "") {
value = JSON.parse(localStorage.getItem(localStorage.key(i)));
for (j = 0; j < value.length; ++j) {
addRow(value[j]);
}
}
}
}
for (i = 0; i < localStorage.length; ++i) {
li = document.createElement('li');
li.className = "category";
li.innerHTML = "<a href='#'>" + localStorage.key(i) + "</a></li>";
document.getElementById("categories").appendChild(li);
}
categories = document.getElementsByClassName("category");
for (i = 0; i < categories.length; ++i) {
categories[i].addEventListener("click", getPostSorter(i));
}
} else {
alert("Uw browser ondersteunt geen localStorage. Gebruik alstublieft een nieuwere browser zoals Google Chrome, Mozilla Firefox of > Internet Explorer 7");
}
};
Could anyone tell me why these are wrong and what I should do to fix them? I've googled some more information but I wasn't able to actually find anything helpful. I've tried adding "new" to the SortPosts but then it gave me the message Do not use 'new' for side effects.
Missing 'new'.
SortPosts(categories[categoryNumber].textContent);
Functions with names starting with capital letters are, by convention, constructor functions. Yours is not. Rename the function to sortPosts.
Unexpected '('.
if (typeof (Storage) !== "undefined") {
typeof is an operator, not a function.
Use typeof Storage not typeof (Storage).
line 65 character 9Unexpected 'typeof'. Use '===' to compare directly with undefined.
Don't use typeof. Use Storage !== undefined.
NB: JSLint is a very opinionated linter. It is possible for undefined to be overridden. I prefer the typeof approach.
To fix these issues, change line 45 to this:
newSortPosts(categories[categoryNumber].textContent);
Renaming SortPosts to newSortPosts in your code.
On line 65 you don't need to compare the typeof, rather you can just see if Storage is undefined:
if (Storage !== undefined) {
Just a note you when using typeof, you don't need parentheses as typeof is an operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
The script works by asking user for add or remove an item in the array. Then asks to continue this loop. The problem here is that my script doesn't seem to match my user's input (removeItem) to the item in the list (myList[i]). I'm at a lost as to why this is failing to match.
// new method for removing specific items from a list
Array.prototype.remove = function(from,to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
printList = function() {
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
document.write(i + ":");
document.write(myList[i] + "<br/>");
};
document.write("<br/><br/>");
};
// initial list
var myList = new Array ();
if (myList.length === 0) {
document.write("I have " + myList.length + " item in my list. It is: <br/>");
}
else {
document.write("I have " + myList.length + " items in my list. They are: <br/>");
}
printList();
var continueAdding = "yes";
var askToContinue = "";
while (continueAdding === "yes") {
// loop
var askUser = prompt("What do you want to [A]dd or [R]emove an item to your inventory?").toUpperCase();
switch (askUser) {
case "A": { // add an user specified item to the list
var addItem = prompt("Add something to the list");
myList.push(addItem);
printList();
break;
}
case "R": { // remove an user specified item from the list
var removeItem = prompt("what do you want to remove?");
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
break;
}
if (myList.length === 0) {
myList[0] = "Nada";
}
};
printList();
break;
}
default: {
document.write("That is not a proper choice.");
}
};
askToContinue = prompt("Do you wish to continue? [Y]es or [N]o?").toUpperCase(); // ask to continue
if (askToContinue === "Y") {
continueAdding = "yes";
}
else {
continueAdding = "no";
}
}
Your loop never allows it to loop through all the items, because it breaks on the first iteration if the item doesn't match.
The break statement should be in the if block, not in the else block - use this instead:
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
break;
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
}
};
if (myList.length === 0) {
myList[0] = "Nada";
}
Also, note that it's looking for an exact match, case sensitive, same punctuation, and everything. If you want it to be a little more lenient you'll need to modify the script to convert both strings to lowercase and strip punctuation before comparing them.
Edit: Just noticed something else -- testing for an empty list needs to be done outside the loop. I updated the above code to reflect this.