detect whether variable contains letters or numbers javascript - javascript

I've been looking on the internet but couldn't find a proper solution to my problem.
I have two use inputs. One is Age. The other is Name.
Age must be a number. Name must be a word, containing only characters.
if(age==number $$ name == characters){
// do something
}else{
// do something else
}
I tried:
if(Math.floor(num) == num $$ Math.floor(name) != name){
// do something
}else{
// do something else
}
But no luck whastsoever.
If you know how to do this could you let me know. Thanks a lot.

The regex solution is probably the simplest given that your input will be strings anyway.
Try this:
if (/^\d+$/.test(age) && /^\D+$/.test(name)) {...}
The main difference with the ones posted above is in the ^ and $; these will make sure that the string containts only the specified character, as opposed to them containing at least one.

You could do this
if (+age==age && name!=+name) {
It checks that both conditions are verified :
age strictly contains a number
name isn't a number
But it's hard to define a strict rule for a name. Here's a name in my country : "Dupé d'Egïe"
Supposing you'd want to accept for the name only "Letters from a-z and spaces" (which is probably a bad idea), then you may do
if (+age==age && /^[a-z ]+$/.test(name)) {
To test if age contains only digits and name contains no digit, you may do
if (/^\d+$/.test(age) && /^\D+$/.test(name)) {

You could use the javascript function parseInt(value), if the result is NaN, It's not a number
if(parseInt("54")) {
console.log("It's a number");
} else {
console.log("It's not");
}

Related

If string does NOT contain value [duplicate]

I am currently trying to figure out how to solve the above named problem.
Specifically I want to check if the string does not contain the word "stream" both in capital and lowercase letters.
Here's my code so far:
if (((gewaesser_name1.includes("Stream") == "false") ||
(gewaesser_name1.includes("stream") == "false")) &&
((gewaesser_name2.includes("Stream") == "false") ||
(gewaesser_name2.includes("stream") == "false")))
{var a= "..."}
The code does obviously not work as the results are not what I expect them to be.
I also tried to use the indexOf method before using the following syntax variations:
gewaesser_name2.indexOf("stream") == -1
gewaesser_name2.indexOf("stream") < 0
None of these variations seem to work for me. Could anyone please give me a hint what's the problem here? I used the indexOf method before many times but always when I wanted to check if a string did contain a specific word, not the other way round.
I suggest to use String+toLowerCase and check with String#indexOf, because it works in every browser.
if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1) {
var a = "..."
}
indexOf() is the correct approach and the case issue can be easily resolved by forcing the test string to lower or upper case before the test using .toLowerCase() or .toUpperCase():
const lookupValue = "stream";
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
function testString(testData, lookup){
return testData.toLowerCase().indexOf(lookup) === -1;
}
function prettyPrint(yesNo){
return "The string does" + (yesNo ? " NOT" : "") + " contain \"stream\" in some form."
}
console.log(prettyPrint(testString(testString1, lookupValue)));
console.log(prettyPrint(testString(testString2, lookupValue)));
You may want to compare the returned results of your include() with strictly equal operands, === false or === true, it's much better practice however not really needed for this, just looks like you might benefit from knowing the different as comparing boolean to a string is an odd thing to do. I'd also not be checking "Stream" and "stream" try using toLowerCase() instead like so, var str1_check = gewaesser_name1.toLowerCase();
I'd check for stream using the lowercase "stream" as your new strings will all be in lower case, as well you want them to be separate from your initial variables as you may not want those names forced to lowercase. I'd use str1_check.includes("stream") to check if this string has the string "stream" in it, because this result is truthy or falsey you can perform your check like so.
if(str1_check.includes("stream")) {
//this string contained stream
}
I looks like your if logic here was if the first name doesn't contain "stream" or name 1 and 2 do not contain stream but your checking name 1 with lowercase "stream" and name 2 with uppercase "stream". it looks like you just want both names not to contain stream, this can be much more easily performed like this.
var str1_check = gewaesser_name1.toLowerCase(),
str2_check = gewaesser_name2.toLowrCase();//this way you're not making multiple toLowerCase calls in your conditional and maintain the state of your two names.
if(!str1_check.includes("stream") && !str2_check.includes("stream")){
//your code on truthey statement
}
Thanks for the fast feedback guys, the code is now running perfectly fine!
I am using the following code:
`if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1)
{var a = "does NOT contain stream"}
else {var a= "does contain stream"}
`
this is a operation you can do in regex:
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
const re = /stream/i
console.log( !!(testString1.match(re) ));
console.log( !!(testString2.match(re) ))
I would prefer to use javascript RegExp like this:
function includesMatch(lookupValue, testString){
var re = new RegExp(lookupValue, 'i'); //Here the 'i' means that we are doing a case insensitive match
return testString.match(re) !== null
}
var lookup = "stream";
var test1 = "do I have a StrEAm in me?";
var test2 = "well at least I don't";
console.log(includesMatch(lookup, test1));
console.log(includesMatch(lookup, test2));

How can I correctly check if a string does NOT contain a specific word?

I am currently trying to figure out how to solve the above named problem.
Specifically I want to check if the string does not contain the word "stream" both in capital and lowercase letters.
Here's my code so far:
if (((gewaesser_name1.includes("Stream") == "false") ||
(gewaesser_name1.includes("stream") == "false")) &&
((gewaesser_name2.includes("Stream") == "false") ||
(gewaesser_name2.includes("stream") == "false")))
{var a= "..."}
The code does obviously not work as the results are not what I expect them to be.
I also tried to use the indexOf method before using the following syntax variations:
gewaesser_name2.indexOf("stream") == -1
gewaesser_name2.indexOf("stream") < 0
None of these variations seem to work for me. Could anyone please give me a hint what's the problem here? I used the indexOf method before many times but always when I wanted to check if a string did contain a specific word, not the other way round.
I suggest to use String+toLowerCase and check with String#indexOf, because it works in every browser.
if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1) {
var a = "..."
}
indexOf() is the correct approach and the case issue can be easily resolved by forcing the test string to lower or upper case before the test using .toLowerCase() or .toUpperCase():
const lookupValue = "stream";
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
function testString(testData, lookup){
return testData.toLowerCase().indexOf(lookup) === -1;
}
function prettyPrint(yesNo){
return "The string does" + (yesNo ? " NOT" : "") + " contain \"stream\" in some form."
}
console.log(prettyPrint(testString(testString1, lookupValue)));
console.log(prettyPrint(testString(testString2, lookupValue)));
You may want to compare the returned results of your include() with strictly equal operands, === false or === true, it's much better practice however not really needed for this, just looks like you might benefit from knowing the different as comparing boolean to a string is an odd thing to do. I'd also not be checking "Stream" and "stream" try using toLowerCase() instead like so, var str1_check = gewaesser_name1.toLowerCase();
I'd check for stream using the lowercase "stream" as your new strings will all be in lower case, as well you want them to be separate from your initial variables as you may not want those names forced to lowercase. I'd use str1_check.includes("stream") to check if this string has the string "stream" in it, because this result is truthy or falsey you can perform your check like so.
if(str1_check.includes("stream")) {
//this string contained stream
}
I looks like your if logic here was if the first name doesn't contain "stream" or name 1 and 2 do not contain stream but your checking name 1 with lowercase "stream" and name 2 with uppercase "stream". it looks like you just want both names not to contain stream, this can be much more easily performed like this.
var str1_check = gewaesser_name1.toLowerCase(),
str2_check = gewaesser_name2.toLowrCase();//this way you're not making multiple toLowerCase calls in your conditional and maintain the state of your two names.
if(!str1_check.includes("stream") && !str2_check.includes("stream")){
//your code on truthey statement
}
Thanks for the fast feedback guys, the code is now running perfectly fine!
I am using the following code:
`if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1)
{var a = "does NOT contain stream"}
else {var a= "does contain stream"}
`
this is a operation you can do in regex:
const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
const testString2 = "I might contain the word steam and it might be capitalized any way.";
const re = /stream/i
console.log( !!(testString1.match(re) ));
console.log( !!(testString2.match(re) ))
I would prefer to use javascript RegExp like this:
function includesMatch(lookupValue, testString){
var re = new RegExp(lookupValue, 'i'); //Here the 'i' means that we are doing a case insensitive match
return testString.match(re) !== null
}
var lookup = "stream";
var test1 = "do I have a StrEAm in me?";
var test2 = "well at least I don't";
console.log(includesMatch(lookup, test1));
console.log(includesMatch(lookup, test2));

check a textbox for invalid characters using js and regular expressions

I am having a hard time figuring out how RegExp work.
I need to rewrite some ASP code into html and js, and I've hit an obstacle in this part:
<asp:RegularExpressionValidator runat="server" id="RegExpValidator" controltovalidate="FileName" Display="Dynamic" ValidationExpression="[^#%&*:<>?/{|}]+">
Now, what I do is create an input textbox which will run a js function whenever its content is changing.
<input type="text" id="fileNameTextBox" class="ms-input" size="35" maxlength="123" onchange="regexValidator(this);"/>
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else {
// Regex stuff goes in here
}
}
Now, for the life of me I can't figure out how to construct the regular expression. The ValidationExpression field i assume checks for invalid characters though it doesn't seem to be a properly constructed regex, and I can't figure out how to write it into a proper one to use with js. Could someone help me out with this?
If you want the regex to check for invalid characters in the field, you can use this.
^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$ This will give you a match if there is at least one invalid character.
You are almost there. Now you just need to make sure, that your string only consists of valid characters. Do this by adding anchors for the beginning and end of string, thus ensuring that the repeated sequence covers the whole string:
ValidationExpression="^[^#%&*:<>?/{|}]+$"
EDIT: I just realised that you probably also want to know how to create a regular expression from a string. You can simply pass a string to a regex constructor:
new RegExp(validationExpressionGoesHere);
[^#%&*:<>?/{|}]+ looks like a valid expression to me (although typically regular expressions are enclosed in forward-slashes). It's basically checking to see of the filename contains any of the illegal characters within the square brackets (apart from the caret ^ which indicates negation).
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else if(val.match(/[^#%&*:<>?/{|}]+/)) {
// Valid
}
else {
// Invalid
}
}

I want regular expression for age field in javascript

var text6 = document.getElementById("text6").value;
var regularExpression1 = /^[1-9]?[0-9]{1}$|^100$/;
if (!text6.match(regularExpression1)){
alert("Please enter Valid Age");
return false;
}
This code is not working properly
Don't use a regexp. Use this function for checking whether something is a number
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
And for your case
function isIntegerBetween0And100(n) {
return isNumber(n) && n>0 && n<=100 && n%1===0;
}
Much faster :)
Your regex is using | but without ().
/(^[1-9]?[0-9]{1}$|^100$)/ would work, but it could be better. This expression can be simplified to /^([1-9]?\d|100)$/, i.e. there's no need to repeat ^ or $, [0-9] can be \d, and {1} is always unnecessary.
I'm not sure regex is best for validating an age, I'm not sure why you can't just simplify it to /^\d{1,3}$/. Things can be older than 100, even people.
I would also validate fields using /regex/.test() instead of string.match(/regex/).
If you have an age range limit, then test that in 'normal code' not regex, it would be easier to follow and modify (if your upper limit changes).

Chars in Javascripts function returing false even though charcters do not satisify if condition

I am trying to learn JavaScript... I have function like, I take the format user id field... which is an email address and try to check if it matches below condition. However even thought I give the user name >3 and domain as gmail.com, I still get false return...Can someone please check and let me know why it is going into the if loop, do I have to trim the text or something.
Also if you can tell me how to write this effectively using jQuery that would help me learn. But if you think I am mixing two thing here... My priority is first question above.
function isValidate(eltt) {
var flag = true;
var upos = eltt.indexOf("#");
var uendpos = eltt.indexOf(".com");
var totlength = eltt.length;
var domain = eltt.slice(upos,totlength);
if ( upos < 3 | domain!="gmail.com" | uendpos=== -1) {
flag=false;
}
return flag;
}
First, the problem is that you're using | instead of ||. (The | is a bitwise or, which in this case will yield a basically random result by combining the bits of the binary representation of your conditions. Chances are, you'll never need |; so use || and forget that | even does anything by itself.)
Second, this validation would be easier with a regular expression:
if (!eltt.match(/^.{3,}#gmail\.com$/)) {
return false;
}
That is, it must start with (^) at least three characters .{3,}, followed by the literal text #gmail.com, with nothing after it ($).

Categories