What is the regex of 'if'? - javascript

I am working on a project that needs to check if the user has written a good condition on a textfield. So I'd like to know if one of you knows the regex of a 'if'. For example, if the user writes if ((k <= 5 && k>0)|| x>8) I will return true.

Keith's reference looks good (pegjs.org). You're not looking for a regex (albeit possible to do with such) by a lexer + yacc combo (see flex and bison). Note that what you are really looking for is the "expression" parser. A "simple calculator" expression.
One way to test would be to use the "eval()" function. However, it is considered to be a dangerous function. Yet, in your case you let the end user enter an expression and then execute that expression. If they write dangerous stuff, they probably know what they are doing and they will be doing it to themselves.
There is documentation about it:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
In your case you would do something like the following with a try/catch to know whether it is valid:
var valid = true;
try
{
// where input.val would reference your if() expression
eval(input.val);
}
catch(e)
{
valid = false;
}
Note that's a poor man solution since it won't tell you whether other code is included in the expression. There are probably some solution to that such as adding some string at the start such as:
eval("ignore = (1 + " + input.val + ")");
Now input.val pretty much has to be an expression. You'll have to test and see whether that's acceptable or not.

Related

How to accept an input in the console from the user (JS)?

I tried to create a JavaScript program that outputs the binary format of an English letter on input. I had to put the value in the code. How can the value be entered in the console when the program runs?
function returnBinaryLetter(char) {
return ((/^[a-z]$/).test(char)) ? char.charCodeAt(0).toString(2).padStart(8, '0') : 'Sorry, that is not a letter.'
}
// Something like:
// const input = consoleInputFunction('Enter a number.');
// console.log(returnBinaryLetter(input.toLowerCase()));
EDIT 1: This is not for a webpage. This is a JS program which I will run using Node.js. I require a solution with just JS, not with some framework (if that is even possible, mentioning just to be specific).
EDIT 2: I have made the code better after suggestions in Endothermic Dragon's answer.
To directly answer your question, you would use prompt to get a user input in this case.
However, you don't need all of that code. Try this:
function returnBinaryLetter(char) {
if ((/^[a-z]$/).test(char)) {
return char.charCodeAt(0).toString(2).padStart(8, '0')
} else {
return 'Sorry, that is not a letter.'
}
}
var input = prompt('Enter letter to be converted to binary:').toLowerCase();
console.log(returnBinaryLetter(input))
While it may seem a bit intimidating, here's the whole thing broken down:
Ask for an input using prompt, and convert it to lowercase.
Pass the character to the function returnBinaryLetter, and log the output.
Now for the function returnBinaryLetter:
Check if it is a single lowercase letter, using some RegEx.
If it is, return binary. Otherwise, return an error with a description.
Hmm, but how does the binary conversion work?
First, take the character and get its character code.
Next, convert that code to binary.
Finally, pad the start so it is an 8-bit number. If it is not 8 digits, add on 0s at the beginning until it is.
Here, you can see that a more dynamic conversion looks much shorter, and cleaner as well, compared to manually entering about 28 lines of code.
Bonus:
Surprise, surprise! You can further shorten it. Using a ternary operator, you can skip the if-else statement.
function returnBinaryLetter(char) {
return ((/^[a-z]$/).test(char)) ? char.charCodeAt(0).toString(2).padStart(8, '0') : 'Sorry, that is not a letter.'
}
var input = prompt('Enter letter to be converted to binary:').toLowerCase();
console.log(returnBinaryLetter(input))
Now, it's a one-liner!
A ternary operator is usually used within variables when you want to assign its value based on a condition. The ternary operator first checks if the condition inside the brackets is true, and if it is, it returns the first statement (between ? and :), and if not, it returns the second statement (after the :). Pairing this with the return statement of a function, you get a one-liner function!
Feedback:
Since it seems that you are following CamelCase, I thought I would mention that function names should always start with a capital letter, along with each word after that also starting with a capital letter. Variables are different however - for variables, you do make the first letter lowercase, but make all the other words uppercase. In addition, the function name returnBinaryLetter might seem intuitive to you, but not for anyone looking at the code. A more intuitive name that exactly describes its function would be LowercaseLetterToBinary.
For NodeJS, You can use inquirer, which provides different kinds of prompts for the command line (such as text, list, checkbox etc).
Prerequistes:
Install it with npm install inquirer
Example
const { prompt } = require("inquirer");
async main() {
const binaryLetter = await prompt({
type: 'input',
name: 'letter',
message: `What's your name >>`
})
.then(answer => returnBinaryLetter(answer['letter']));
}
main();

Regex for js variable end with semicolon

I am trying to find and extract an assignment of a property of the product_image object from Javascript code, extracted with BeautifulSoup. I have tried following
re.findall(r"product_images\['top_lg'] = .*;", txt)
Unfortunately it does not extract anything from my text below.
product_images['top_lg'] = {
"tn": '//image.test.com/media/cache/04/0a/040a1e61f5edc387d8c8e40d3ea0e0ca.jpg',
"md": '//image.test.com/media/cache/b7/f3/b7f3cb1da267d7e8ac0412bdc522c862.jpg',
"lg": '//image.test.com/media/shape_images/011f7f24ae4cbbef191cff1a711df9e1_a3c9ca71b7d85d87085955f8d1c4bfc3_0_.jpg',
"alt": 'test ',
"data-zoomable": 'True',
"text_line": 'teest'
};
The scripts that I am parsing are taken from https://www.brilliantearth.com/Petite-Twisted-Vine-Diamond-Ring-White-Gold-BE1D54-3821855/
If, like me, you find regex flags confusing and hard to remember, use
"not semicolon" expressions instead of dot
re.findall(r"product_images\['top_lg'] = [^;]*;", txt)
Note. Otherwise you can add a flag as Thierry suggests, though you would need also add a 'non-gready modifier' ? after * to indicate that you are interested in the first semicolon rather that the last.

How to make an emitter ignore case?

bot.on('message', message => {
var str = (message.content.indexOf("swear"))
if (str != -1){
var Pottymouth = message.guild.roles.find('name', 'Pottymouth')
message.channel.send("Woah there, " + message.author + ", you can't use that kind of language here!");
message.member.addRole(Pottymouth);
}
I'm trying to code Jesus as a super cool bot, and one thing he needs to do is make sure that nobody's swearing. So far, this code works for when someone says "swear", but it won't detect them saying "SWEAR" or any other capitalisation. How do I make Jesus not bother with listening to case, and instead focus on the actual content of the message?
Simply lowercase the whole message before checking, or else consider using a case-insensitive regular expression.
Using a regular expression allows you to enforce word boundaries as well, which means you can avoid flagging false positives like "menswear".
if (/\bswear\b/.test(message)) {
// Do things
}

how to evaluate a expression x+3x-4 by passing different values x to find the output

Ho to evaluate a scientifc expression (x+3x-4+sin x) by passing different values x to find the output
Please let me know the inbuilt function that can be used in java
Well I am not going give the whole code to you, but here are some hints:
The best way to eval an expression without any external API would be using running the expression as a javascript code and get the result.
Since you just can't do sin(0) + 6 in javascript, you will have to use RegEx to replace all function name to Math.(function name here) without affecting other function name. Such as sin(0) + asin(0)will be replaced to Math.sin(0) + Math.asin(0).
The changing value of x is very simple, just use RegEx to replace the x to a value without affecting other stuff, like x + exp(1) will be turned to 0 + Math.exp(1)
User can run javascript code with your calculator if using javascript, please be careful not to allow users to do so.
Similar question have been asked before, you might want to take a look about it: Evaluating a math expression given in string form
You’re looking for the sin method present in the Math library.
An example:
Math.sin(25); // Returns ‘sin’ of the value ‘25’

jQuery / Javascript substitution 'Syntax error, unrecognized expression'

I am implementing jQuery chaining - using Mika Tuupola's Chained plugin - in my rails project (using nested form_for partials) and need to dynamically change the chaining attribute:
The code that works without substitution:
$(".employee_title_2").remoteChained({
parents : ".employee_title_1",
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
The attributes being substituted are .employee_title_1 and .employee_title_2:
var t2 = new Date().getTime();
var A1 = ".employee_title_1A_" + t2;
var B2 = ".employee_title_2B_" + t2;
In ruby speak, I'm namespacing the variables by adding datetime.
Here's the code I'm using for on-the-fly substitution:
$(`"${B2}"`).remoteChained({
parents : `"${A1}"`,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
Which throws this error:
Uncaught Error: Syntax error, unrecognized expression:
".employee_title_2B_1462463848339"
The issue appears to be the leading '.' How do I escape it, assuming that's the issue? Researching the error message Syntax error, unrecognized expression lead to SO question #14347611 - which suggests "a string is only considered to be HTML if it starts with a less-than ('<) character" Unfortunately, I don't understand how to implement the solution. My javascript skills are weak!
Incidentally, while new Date().getTime(); isn't in date format, it works for my purpose, i.e., it increments as new nested form fields are added to the page
Thanks in advance for your assistance.
$(`"${B2b}"`).remoteChained({
// ^ ^
// These quotes should not be here
As it is evaluated to a string containing something like:
".my_class"
and to tie it together:
$('".my_class"')...
Same goes for the other place you use backtick notation. In your case you could simply use:
$(B2).remoteChained({
parents : A1,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
The back tick (``) syntax is new for Javascript, and provides a templating feature, similar to the way that Ruby provides interpolated strings. For instance, this Javascript code:
var who = "men";
var what = "country";
var famous_quote = `Now is the time for all good ${who} to come to the aid of their #{what}`;
is interpolated in exactly the same way as this Ruby code:
who = "men"
what = "country"
famous_quote = "Now is the time for all good #{who} to come to the aid of their #{what}"
In both cases, the quote ends up reading, "Now is the time for all good men to come to the aid of their country". Similar feature, slightly different syntax.
Moving on to jQuery selectors, you have some flexibility in how you specify them. For instance, this code:
$(".my_class").show();
is functionally equivalent to this code:
var my_class_name = ".my_class";
$(my_class_name).show();
This is a great thing, because that means that you can store the name of jQuery selectors in variables and use them instead of requiring string literals. You can also build them from components, as you will find in this example:
var mine_or_yours = (user_selection == "me") ? "my" : "your";
var my_class_name = "." + mine_or_yours + "_class";
$(my_class_name).show();
This is essentially the behavior that you're trying to get working. Using the two features together (interpolation and dynamic jQuery selectors), you have this:
$(`"${B2}"`).remote_chained(...);
which produces this code through string interpolation:
$("\".employee_title_2B_1462463848339\"").remote_chained(...);
which is not correct. and is actually the cause of the error message from jQuery, because of the embedded double quotes in the value of the string. jQuery is specifically complaining about the extra double quotes surrounding the value that you're passing to the selector.
What you actually want is the equivalent of this:
$(".employee_title_2B_1462463848339").remote_chained(...);
which could either be written this way:
$(`${B2}`).remote_chained(...);
or, much more simply and portably, like so:
$(B2).remote_chained(...);
Try this little sample code to prove the equivalence it to yourself:
if (`${B2}` == B2) {
alert("The world continues to spin on its axis...");
} else if (`"${B2}"` == B2) {
alert("Lucy, you've got some 'splain' to do!");
} else {
alert("Well, back to the drawing board...");
}
So, we've established the equivalency of interpolation to the original strings. We've also established the equivalency of literal jQuery selectors to dynamic selectors. Now, it's time to put the techniques together in the original code context.
Try this instead of the interpolation version:
$(B2).remoteChained({
parents : A1,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
We already know that $(B2) is a perfectly acceptable dynamic jQuery selector, so that works. The value passed to the parents key in the remoteChained hash simply requires a string, and A1 already fits the bill, so there's no need to introduce interpolation in that case, either.
Realistically, nothing about this issue is related to Chained; it just happens to be included in the statement that's failing. So, that means that you can easily isolate the failing code (building and using the jQuery selectors), which makes it far easier to debug.
Note that the Javascript syntax was codified just last year with ECMAScript version 6, so the support for it is still a mixed bag. Check your browser support to make sure that you can use it reliably.

Categories