This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 9 years ago.
I have this function
function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp(/^[a-z0-9_-]\w{"+minL+","+maxL+"}$/);
switch(exp.test(str)){
case true: return true;
case false: return false;
}
}
I want to insert minimum Length and maximum length dynamically,
But if above code used,its giving me false whether it should accept the string as true.
can anyone tell me, what should i use rather "+variable+" to insert the value dynamically.
Thanks in advance.
You can use the regex object constructor to build your regex from a string as stated here.
Example taken from linked answer :
var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;
In your case that would do something like :
function validateUsername(str,minL,maxL){// i'm passing validateUsername("asdf_1",2,8)
var exp=new RegExp("^[a-z0-9_-]\w{" + minL + "," + maxL + "}$");
/*
why ???
switch(exp.test(str)){
case true: return true;
case false: return false;
}
*/
return exp.test(str);
}
You can separate length validation from the pattern, something like this
if(str.length<minL || str.length>maxL){
// invalid length
}else{
var exp=new RegExp(/^[a-z0-9_-]\w$/);
return exp.test(str)
}
Related
This question already has answers here:
How to do case insensitive string comparison?
(23 answers)
Closed 2 years ago.
I understand we need to use toUpperCase, but I wasn't sure where to put it. I would like the word "toyota" to be acceptable whether it's uppercase or lowercase.
let correctGuess = false;
let car = "toyota";
let guess = prompt ('guess the car');
if (guess === car){
correctGuess = true;
}
if (correctGuess === true){
console.log ('correct');
}
else {
console.log('incorrect')
}
Convert both of them to either uppercase or lowercase and compare.
Example:
if(guess.toLowerCase() === car.toLowerCase()) {
// your logic
}
Although you have already defined car as lowercase so you don't really need to convert it to lowercase.
Change
if (guess === car){
correctGuess = true;
}
To
if (guess.toUpperCase() === car.toUpperCase()){
correctGuess = true;
}
Kind of redundant but it gets useful if the car variable itself was taken from a user input.
You can also make both .toLowerCase to get the same result, literally no difference
This question already has answers here:
How to check if a variable is an integer in JavaScript?
(41 answers)
Closed 3 years ago.
I need to validate whether a input is a valid integer allowing for +/- entries.
I have tried this.
function valid(elem)
{
var num = parseInt(elem);
if(!Number.isInteger(num))
{
alert ("Not an integer");
}
}
But the issue here is , it is validating even strings like 10sd as an integer. So how to validate this?
I want to validate as following:
valid(-10) = true;
valid(+10) = true;
valid(-10.01) = false;
valid(10sd) = false;
valid(10.23see) = false;
valid(10) = true;
Simple
function valid(elem){return parseInt(elem)==elem}
function valid(value) {
if(typeof value === 'number' && isFinite(value))
alert ("It is an integer");
}
This function does the job, typeof is a keyword in Javascript which tells you the data type of the variable
You can check this out, for more usage of typeof:
https://webbjocke.com/javascript-check-data-types/
Edit: made a silly error in alert, it should alert if it is an integer, the if condition checks for number
This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 3 years ago.
I'm trying to use a onblur function to validate a postcode field which is using a regex expression to test against, However it is returning false when it should be returning true.
JS Fiddle: https://jsfiddle.net/gzr5csu4/2/
function validatePostcode(){
alert("onblur triggered!");
var postcodeRegEx = /^5[0-9]{3}$/;
var postcodeResult = postcodeRegEx.test(postcode);
if (postcodeResult == false){
alert("Postcode is not valid!");
}
return true;
}
I see no reason to why this isn't working, i'm fairly new to java-script so probably missing something very simple.
The onblur function is triggered however when enetering "5251" into the postcode it returns false when it should not.
Any help would be greatly appreciated.
You are missing to declare and set postcode.
Add this var postcode = document.getElementById("postcode").value;
The function should look like this:
function validatePostcode(){
alert("onblur triggered!");
var postcode = document.getElementById("postcode").value;
var postcodeRegEx = /^5[0-9]{3}$/;
var postcodeResult = postcodeRegEx.test(postcode);
if (postcodeResult == false){
alert("Postcode is not valid!");
}
return true;
}
This question already has answers here:
Java, Check if a String is a palindrome. Case insensitive
(5 answers)
Closed 5 years ago.
I am asked to check if a string is a Palindrome.
To not be case sensitive. To ignore all characters that are not letters.
My Answer
function palindrome(str) {
var oldStr = str.toLowerCase().replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '');
var newStr = str.replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '').split("").reverse().join("").toLowerCase();
if ( oldStr === newStr){
return true;
}
else {
return false;
}
}
palindrome("ininiNI");
The function is to be checked with any string possibility.
Example: ("0_0 (: /-\ :) 0-0") Which according to the requirements should return true.
I could not find a better solution in JavaScript then the one above.
Is there a faster/better way than just writing out each possible character to be removed/replaced? (especially since what I wrote is far from exhaustive...)
There is no need to call toLowerCase() and replace() twice. You can also cut string in a half, reverse one part and then compare. That way you can speed up your function few times at least.
Optimized function may look like that:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]/g, '');
var max = str.length - 1;
for (var i = Math.floor(max / 2); i >= 0; i--) {
if (str[i] != str[max - i]) {
return false;
}
}
return true;
}
palindrome("inabcbani"); //true
palindrome("abcddcba"); //true
palindrome("a*#$(b)&^#%#%(*a"); //true
palindrome("abba"); //true
palindrome("abcdba"); //false
For loop will be the fastest way in my opinion as it's quick and simple. You can return false once you find first character that doesn't match.
This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I'd like to achieve that, if "clientpsseabq" string is contained in variable Var_words then equal true, else false. I just have no idea what method or function do I need to use?
var Var_words = "https://www.go.me/outputsearchs/clientpsseabq"
if ( Var_words contains string "`clientpsseabq`"){
return true;
}else{
return false;
}
if someone could help me how can I complete this task?
Use the (native JavaScript) function String.indexOf():
if(Var_words.indexOf('clientpsseabq') !== -1) {
return true;
} else {
return false;
}
.indexOf() returns the index of the string. If the string is not found, it returns -1.
A smaller, cleaner solution would be to simply return the value of the conditional directly:
return (Var_words.indexOf('clientpsseabq') !== -1);
You can try this
if (Var_words.indexOf("clientpsseabq") >= 0)
or with care of case sensitivity
if (Var_words.toLowerCase().indexOf("clientpsseabq") >= 0)
{
// your code
}
use a regular expression to test for the case
if(/clientpsseabq/.test(Var_words)){
//given string exists
} else {
//given string does not exists
}
if(Var_words.indexOf("clientpsseabq") >= 0))
{
}