Accept any value in JavaScript? (Regular expression?) - javascript

I am creating a small very simple game.
I want to know how to accept any input value in the following code...
if(answer === "My name is" + * + "and I am a Leo" ) {
alert("Correct!")
}
To my understanding the asterisks would accept any value input by the user.
Besides that, script breaks after i write the above.
Forgot to add the JSFIddle

Try this:
if (answer.substring(0, 10) == "My name is" && answer.slice(-14) == "and I am a Leo") {
alert("Correct!");
}
substring(0, 10) -> gets the first 10 characters
slice(-14) -> gets the last 14 characters
Here's a regex approach too:
var matches = answer.match(/^My name is (.*) and I am a Leo$/);
if (matches != null) {
alert("Correct!"); //use matches[1] to get the name
}

I assume you have already prompted the user for a value to the answer variable.
You probobly want to use a regeular expression:
if (answer.search(/^My name is.*and I am a Leo$/) === 0) {
alert("Correct!");
}
Look at this cheatsheet to see what the difference characters mean. The search method returns the position of the match in the string, or -1 at failure. In this case, since ^ matches the start of the string, it will always return 0 on success.
$ matches the end of the string and .* means match any character except newline 0 or more times (that is any amount of times).

Related

Regular Expression Returns Undefined

I'm attempting one of the beginner coderByte challenges, Simple Symbols. Challenge summary below.
"Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter."
function SimpleSymbols(str){
var RegExp = /\+\w\+/gi;
var regexp1 = /^\w/gi;
var regexp2 = /\w$/g;
if(regexp1.test(str) == true){
return false
} else if(regexp2.test(str) == true){
return false
} else if(RegExp == true){
return true
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));
The first regular expression I'm testing, /^\w/gi, comes back undefined, and I can't figure out why?
https://regex101.com/ is a great tool I've used before, and my expression does identify f as the first character in the string, but when I test it in codepen, it comes back undefined in the console.
Code
See regex in use here
^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$
Alternatively, using the opposite logic (catching invalid strings instead of valid ones), you can use (?:^|[^+])[a-z]|[a-z](?:[^+]|$)
Usage
Please note the valid/invalid strings below have been created according to the OP's explanation of valid and invalid strings: That each letter must be surrounded by a + symbol. and that the plus sign + may be shared between characters such that +a+a+ is valid (specified in comments below the question).
var a = [
// valid
"++d+===+c++==+a++",
"+a+a+a+",
"+a++a+",
"+a+",
// invalid
"++d+===+c++==a",
"+=d+",
"+dd+",
"+d=+",
"+d+d",
"d+d+"
];
var r = /^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$/mi;
a.forEach(function(s){
console.log(r.test(s));
});
Explanation
^ Assert position at the start of the line
[+=\d]* Match any number of characters in the set (+, =, or digit)
\+ Match a literal plus sign +
(?:[a-z]\+[+=\d]*)+ Match one or more of the following
[a-z] Match a lowercase ASCII letter
\+ Match a literal plus sign +
[+=\d]* Match any number of characters in the set (+, =, or digit)
$ Assert position at the end of the line
It's returning undefined because your expression does not meet any of the criteria. Since you have no else {} defined, than nothing gets returned. Thus you get undefined. Try this:
function SimpleSymbols(str){
var RegExp = /\+\w\+/gi;
var regexp1 = /^\w/gi;
var regexp2 = /\w$/g;
if(regexp1.test(str) == true){
return false
} else if(regexp2.test(str) == true){
return false
} else if(RegExp == true){
return true
} else {
return "catch all here";
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));
You can use a single regex and the string.test() method (which returns just true/false).
Below are 2 different ways (regex) to do it .
First requires a separate + between word chars. Example +a++b+ (true)
^
(?: [+=]* \+ \w \+ [+=]* )+
$
Second can take a common + between word chars. Example +a+b+ (true)
^
(?:
[+=]* \+ \w
(?= \+ )
)+
[+=]*
$
var patt1 = new RegExp("^(?:[+=]*\\+\\w\\+[+=]*)+$");
function SimpleSymbols_1(str){
return patt1.test(str);
}
var patt2 = new RegExp("^(?:[+=]*\\+\\w(?=\\+))+[+=]*$");
function SimpleSymbols_2(str){
return patt2.test(str);
}
console.log(SimpleSymbols_1('+d+=3=+s+'));
console.log(SimpleSymbols_1('f++d+'));
console.log(SimpleSymbols_1('+a+b+c+'));
console.log(SimpleSymbols_2('+a+b+c+'));
console.log(SimpleSymbols_2('+a+=+c+'));
console.log(SimpleSymbols_2('+a++c+'));
Thank you all for throwing some support/comments my way. Again, I am new to JavaScript and Regular Expressions are fairly foreign to me, though I am gaining some traction in understanding them. Here is the updated solution I posted. It's quite convoluted and perhaps a more inelegant and non-simple way to come to the right answer, but it worked.
function SimpleSymbols(str){
var RegExp = /\+[a-z]\+/gi;
var regexp1 = /^[a-z]/gi;
var regexp2 = /[a-z]$/g;
var regexp3 = /[a-z]\=/gi;
var regexp4 = /\=[a-z]/gi;
if(regexp1.test(str) === true){
return false
} else if(regexp2.test(str) === true){
return false
} else if(regexp3.test(str) === true){
return false
} else if(regexp4.test(str) === true){
return false
} else {
return true
}
}
console.log(SimpleSymbols('+d+=3=+s+'));
console.log(SimpleSymbols('f++d+'));
console.log(SimpleSymbols('+d===+a+'));
console.log(SimpleSymbols('+a='));
console.log(SimpleSymbols('2+a+a+'));
console.log(SimpleSymbols('==a+'));
I was sure there had to be a way to use only one regular expression, but again, I'm still very much a novice.
Thanks again everyone.

REGEX in javascript not working for dots (.) in JavaScript

I am using a regex to validate an email address in JavaScript.
The regex is pretty simple. It checks three things: 1)'#' , 2)'.' ('dot' as in something#gmail.com), and 3) 'a-z' in an email address. If all three return true, email address is valid (according to my validation, atleast)
Here is the code:
function checkemail(){
var e = document.getElementById("email").value;
if((e.match(/#/g)==null)||(e.match(/[a-z]/ig)==null)||(e.match(/./g)==null)){
//display error message
}
}
My question is:
(e.match(/./g)==null); //returns false even though there are no dots in the string e
returns false even when there are no dots in string.
For example:
("thisIsMyEmail".match(/./ig))==null //returns false
Why does it return false when it should be true?
/./g (or /./ig) will match any string that as at least one character in it. . is special in regular expressions, it means "any character here."
For an actual dot, escape it with a backslash: /\./g.
First off, you don't need to check if the string is null. Simply use this:
var email = "Godisgood#gmail.com";
if (email.match(/^\S+\#\S+\.\S+$/i)){
alert("Email address passed validation.");
}
you have to escape the .
The unescaped period means matches any character.
Meaning having a string "abc" using your expression would result in an array containing the characters 'a', 'b', and 'c'.
In your snippet the correct answer is
(e.match(/\./g)==null);
This should result to what you're expecting
Try this
(e.match(/\./g)==null);
. matches any character so needs escaping /\./g
I know you have already got the answer.
But I just want to give an advice.
My advice is - don't use the javascript code to validate any email address; because as per your code, #domain., #domain.com these all are also valid email, but everybody knows these are not a valid email address.
So use the below code:
let email = $(this).val();
var positionOfAt = email.indexOf("#");
var positionOfDot = email.lastIndexOf(".");
if(email.search("#") == -1 || //if '#' is not present
email.search(" ") >= 1 || //if blank space is present
email.search(".") == -1 || //if "." is not present
positionOfAt < 1 || //if there is no character before "#", at least one character should be present before "#"
positionOfDot - positionOfAt <= 2 || //between '#' and '.', if there is not at least two character
email.length - positionOfDot <= 2) //if after '.' there is not at least two character)
{
console.log("Invalid email id")
}
else
{
console.log("Valid email id")
}

Test String if each letter has '+' sign on both sides of it

this program is supposed to test str, and if every letter in str has a '+' sign on both sides of it then the function should return true. Otherwise, it should return false. I keep getting the error "SyntaxError: invalid quantifier".
function SimpleSymbols(str) {
var boolean = false;
for(var i=1;i<(str.length-1);i++){
if(/\w/.test(str.charAt(i))){
if(str.charAt(i-1).match('+') && str.charAt(i+1).match('+')){
boolean = true;
}else{
boolean = false;
}
}
}
str = boolean;
return str;
}
match is used for regular expressions, so it's trying to convert '+' to a regular expression, but it's failing because /+/ isn't a valid regular expression (it should be '\\+' or /\+/). But it's easier to just directly test each character, like this:
if(str.charAt(i-1) == '+' && str.charAt(i+1) == '+'){
Also note that /\w/ matches any 'word' character, which includes letters, numbers, and underscores. To mach just letter characters use should use /[a-z]/i (the i at the end makes it case-insensitive, so it will also match upper-case letters).
But it seems a lot simpler to invert the condition. Just test to see if the string contains any letter not surrounded by + signs or a letter at the beginning or end of the string, and return false if it does, like this:
function SimpleSymbols(str) {
return ! /(^|[^+])[a-z]|[a-z]([^+]|$)/i.test(str);
}
Much easier:
function SimpleSymbols(str) {
return !str.match(/[^+]\w/) && !str.match(/\w[^+]/);
}
The main problems with your function are:
You don't test if the first and last characters are letters. It should be safe to run your for loop from index 0 to < str.length because even though this will result in a str.charAt(-1) and str.charAt(str.length) when testing for '+' these just return "" rather than an error. Or of course you could continue with testing from the second character through to the second last in the loop and add an additional test for the first and last characters.
The .match() method does a regex match, so it tries to convert '+' to a regex and of course + has special meaning within a regex and doesn't match the literal. I'd suggest just using === '+' instead, though you could use .match(/\+/).
You are returning whatever value the boolean variable ends up with, which means your function is ignoring the tests on all but the second-last character in the string. You should return false immediately if you find a letter that doesn't have '+' around it.
Your question asked about "letters", but /\w/ doesn't test for a letter, it tests for letters or digits or underscores. If you actually want just letters use /[a-z]/i.
(Also there's no point assigning str = boolean, because JS function parameters are passed by value so this assignment won't affect anything outside the function.)
So:
function SimpleSymbols(str) {
for(var i=0;i<str.length;i++){
if(/[a-z]/i.test(str.charAt(i))){
if(str.charAt(i-1)!='+' || str.charAt(i+1) != '+'){
return false;
}
}
}
return true;
}

Javascript - search a string from beginning

Hello i currently have this part of the code that i developed but i want to do some edits:
$('#target').keydown(function(event) {
if (event.which == 13)
{
var users = ["Dennis Lucky","Lucy Foo","Name Lastname","Billy Jean"];
var match = 0;
var str = $('#target').val();
for(i=0;i<users.length;i++)
{
if ( users[i].toLowerCase().indexOf(str.toLowerCase()) > -1 )
{
match++;
name = users[i];
}
}
if(match == 1)
{
$('#target').val('');
$('#chatbox').append('<span style="color:blue;">'+name+'</span> ');
console.log(name);
}
else if (match >= 2)
{
console.log("many entries");
}
}});
The idea is that if i type something and hit enter if the partial string exists in users becomes blue color.With this code i have the problem that if i write "Lu" i get 2 results, "Dennis Lucky" and "Lucy Foo".
I want to change my code so when i type "Lu" it will start searching the words starting with this sting and not include it.
if ( users[i].toLowerCase().indexOf(str.toLowerCase()) > -1 )
The condition is true if indexOf's returned value is greater than -1. In JavaScript, indexOf returns -1 if a match "needle" (the string you're searching for) isn't found in your "haystack" (the string that you're searching within). Otherwise, it returns the first index of the "needle" in your "haystack".
To explain my terminology of indexOf, here's an example:
haystack.indexOf(needle); // How to use the indexOf function
console.log("apples oranges apples".indexOf("apples")); // This would print 0.
console.log("apples oranges apples".indexOf("white")); // This would print -1.
If you want to ensure that the string starts with the "needle", you simply need to change your code to
if ( users[i].toLowerCase().indexOf(str.toLowerCase()) == 0 )
If you want your "words" ("Lucy Foo" would be "Lucy" and "Foo"), either split your name strings by a space character and perform the indexof search with the elements of the resultant array, or turn to regex.
It is better to use regexes. Since you want to search the start of string use ^
Refer Regular Expressions documentation on MDN for more information.

javascript number validation function

i need a javascript function that able to check for digit and - only.
example: 1,2,3,4,5,6,7,8,9,0 will return true
and - will return true as well.
other than that all return false including enter is pressed.
i have a function like this:
function IsNumeric(sText){
var filter = /^[0-9-+]+$/;
if (filter.test(sText)) {
return true;
}else {
return false;
}
}
i call it like this:
if(!IsNumeric(value)) {
alert("Number and - only please");
}
for some reason it does not work, any method to do the verification without using regex?
EDIT: OK, updated as per your comment, an expression to match either a lone minus sign or any combination of digits with no minus sign:
function IsNumeric(sText){
return /^(-|\d+)$/.test(sText);
}
If you want only positive numbers and don't want to allow leading zeros then use this regex:
/^(-|[1-9]\d*)$/
Regarding your question "any method to do the verification without using regex?", yes, there are endless ways to achieve this with the various string and number manipulation functions provided by JS. But a regex is simplest.
Your function returns true if the supplied value contains any combination of digits and the plus or minus symbols, including repeats such as in "---+++123". Note that the + towards the end of your regex means to match the preceding character 1 or more times.
What you probably want is a regex that allows a single plus or minus symbol at the beginning, followed by any combination of digits:
function IsNumeric(sText){
return /^[-+]?\d+$/.test(sText);
}
? means match the preceding character 0 or 1 times. You can simplify [0-9] as \d. Note that you don't need the if statement: just return the result from .test() directly.
That will accept "-123", "123", "+123" but not "--123". If you don't want to allow a plus sign at the beginning change the regex to /^-?\d+$/.
"example: 1,2,3,4,5,6,7,8,9,0 will return true and - will return true as well."
Your example seems to be saying that only a single digit or a single minus sign is considered valid - if so then try this:
function IsNumeric(sText){
return /^[\d-]$/.test(sText);
}
How about
function IsNumeric(s) {
return /^(+|-|)\d*$/.test(s);
}
Hiphen(-) has special meaning so use escape character in character set.
Try this:
var filter = /^[0-9\-]+$/;
Can be simple ... try this:
function IsNumeric(str) {
return str.length == 1 && (parseInt(str) < 10 || str == "-");
}

Categories