var existing = "";
if(disk.isLinux){
var valinvalid = "/usr" ;
var valinput = /^\/[a-zA-Z]{2,}/ ;
if(!valinput.match(valinvalid)){
return "^/" + existing + "[^/][a-zA-Z]{2,}[^/]$";
}
}
Here im trying to do the following in the first if condition ie. if(disk.isLinux):
1. there should be minimum 3 characters
2. the first character should be /
3. the entire input shouldnt match "/usr". But it can be /us or /usra
If you are just trying to test if it matches, us test on regexp:
/^\/[\w]{2,}/.test("/usr/"); //true
Is this what you are trying to do?
A couple of things:
1) vars should never ever ever be inside if statements
2) String.prototype.match exists RegExp.prototype.match does not
But more importantly, you dont need regEx at all
if (
input.length < 3 ||
input.charAt(0) !== '/' ||
input === '/user'
) {
throw new Error("I'm not happy with the input");
}
try changing your code to use:
var valinput = new RegExp("/^\/[a-zA-Z]{2,}/") ;
if(!valinput.test(valinvalid)){
Related
So I have a function that checks if the last character in a string is an arithmetic operator(+,-,*,/), and if it is it should immediately return from the function. If not, the subtract sign should be appended to the string. However, only the second case seems to be occurring and I can't figure out why. If anyone could provide some insight I would be very appreciative.
$("#subtract").click(function () {
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
var signs=["+","-","*","/"];
var charpos=sliced.charAt(sliced.length -1);
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
else {
var newdisplay=sliced + "-";
$("#display").text(newdisplay);
}
});
You're slicing the input which is removing the last character, then using charAt and getting the second to last character.
var original=$("#display").text(); // "foobar"
var sliced=original.slice(0,original.length - 1); // "fooba"
var charpos=sliced.charAt(sliced.length -1); // "a" -- we lost the "r"
You only need to call charAt and work with the last character (or, if you prefer slice, it's able to accept a negative number and backtrack the string).
Secondly, since signs is an array, you can use indexOf over checking each element. e.g.
var original = $('#display').text();
var signs = ["+","-","*","/"];
var lastChar = original.slice(-1); // OR original.charAt(original.length - 1);
// Check for the lastChar in the signs array
if (signs.indexOf(lastChar) != -1){ // -1 == not found
return; // short exit
}
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
the second line gets rid of the last character in your string. so you're not even able to check what that was. just get rid of it and change the first line to
var sliced=$("#display").text();
and everything should work fine
Instead of
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
try
if ($.inArray(charpos, signs) > -1) {
return;
}
First of all, never enumerate items from an array in such a fashion - it's easy to miss items that way. Secondly, exact instance comparison (===) won't fire, unless you compared exact same strings.
Besides, consider revising how you extract the last character.
After splitting a set of glossary terms with:
lines = text.split(/[\r\n]+/);
I then iterate through the array and parse out each term to properly format them during output. However, a simple check for empty strings has become much more of a headache than I could've ever imagined. Console logging gives me this:
...
"Pushing" "dyspnea: Labored or difficult respiration." //correct
"Pushing" ""
...
Things I have tried in order to find these empty strings:
line === ""
line.length == 0
if(line)
isNaN(line.charCodeAt(0))
typeof line == "undefined"
And various combinations of the list above. On recommendation from a coworker, I checked the line endings of the input text, but it all seemed normal.
I'm sure I'm just doing something really stupid, but the solution has eluded me for far too long. Any help/suggestions would be greatly appreciated!
Edit:
Thanks for the suggestions everyone. Alas, the problem persists...
Also, I forgot to mention, but I have tried both trimming and replacing whitespace in each line after the split, but came up with nothing.
As requested, here is more relevant code.
var text = "";
var end = /\x2E\s\x5B/gm; // ". ["
var lines = [];
var terms = [];
text = document.getElementById("terms").value;
lines = text.split(/[\r\n]+/);
parseText();
function parseText() {
var i = 0;
while(i < lines.length) {
var line = lines[i];
endIndex = lines[i].search(end);
if(line != "" || line != " " || line.length != 0 ) {
parseTerm(lines[i].substring(0, endIndex+1));
}
i++;
}
As the previous answer stated issue is probably whitespace, you can use the trim function to shorten your code:
if (line.trim() == "") {
alert("Blank");
}
maybe string is not a "", but " "?
so check not only zero length, but "white space"
if(st1 == "" || st1 == " " || st1.length == 0 ){
console.log("find empty")
}
Turns out that in my input there was a line with two spaces. I have NO idea why this was causing problems, considering the split was specifically on the pattern described above, but replacing instances of too much whitespace fixed the issue. The new line:
text.replace(/\s\s+/g, " ").split(/[\r\n]+/);
Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.
Here is my jsFiddle
Its on the Phone method, no the name one
Now is this line right? I only want it to be true if the first 3 letters are 087
var RightStarting3 = value.substring(0,2) == (087);
if (BlankPass || LessThan10 || RightStarting3 || GreaterThan10 || (HasSpaces > 0))
{
document.getElementById('Phone').style.background = "red";
return false;
}
else {
document.getElementById('Phone').style.background = "white";
document.getElementById("PhoneTick").style.visibility="visible";
return true;
}
var RightStarting3 = value.substring(0,3) === ('087');
value.substring(x) returns a string and 087 and 87 mean the same to javascript interpreter. You should change one of the datatypes so that they match...
Either the substring to an integer:
var RightStarting3 = parseInt(value.substring(0,2)) == 87;
Or the value you're comparing against to a string:
var RightStarting3 = value.substring(0,3) == "087";
Secondly -- you are invoking ValidateName() immediately (in your assignment to NamePass). Is this really necessary? There will be empty values on page load.
I think with the javascript substring(x,y) method, the y value is the value at which to stop the selection. So in your example the first 3 characters will not be selected and instead the first 2 characters will be selected.
var a = "123";
// this returns "12"
alert(a.substring(0,2));
You probably want to use var RightStarting3 = value.substring(0,3) == ('087'); instead.
KingKongFrom's answer is correct, I would add that you should make sure that value (whatever that is) isn't null first, cause if you try to call substring on null it will thrown an exception and die.
I have to do image size validation using JavaScript. The sizes are provided as text, in the form nXn — e.g. “5X4” or something.
I have done a test for whether the provided size contains an “X”:
if(inputVal.indexOf("X")==-1)
{
$('#erSize').append("*Size should be (e.g) 6X4");
}
But this test accepts e.g. “aXg” also.
How can I check that the values entered either side of "X" are only integers?
Use Regular Expressions
var pattern = /[0-9]\X[0-9]/;
inp = "AXG"; //Sample
if(!pattern.test(inp))
alert("Error");
http://jsfiddle.net/hFTJb/
if(/^\d+X\d+$/.test(inputVal)) // add i after the pattern to match x case-insensitive
{
$('#erSize').append("*Size should be (e.g) 6X4");
}
// accepts "1X1"
// accepts "9999X9999"
// rejects "aaa1X1aaa"
RegEx is probably the best way, I'll give "raw" example without regular expressions that is doing the same thing:
function ValidateImageSize(imgSize) {
var arrDimensions = imgSize.toUpperCase().split("X");
if (arrDimensions.length != 2)
return false;
var w = arrDimensions[0] * 1;
var h = arrDimensions[1] * 1;
return !isNaN(w) && !isNaN(h) && w > 0 && h > 0;
}
Usage:
if (!ValidateImageSize(inputVal)) {
$('#erSize').append("*Size should be (e.g) 6X4");
}
Giving it as it's more readable than RegEx and you can control and understand each step.
Live test case.
You can easily do that by using the RegEx.
Use the regular expression as /(\d+)X(\d+)/g
function isValidInput() {
var regex = new RegExp(/(\d+)X(\d+)/g);
var match = regex.exec(inputVal);
if (match == null) {
$('#erSize').append("*Size should be (e.g) 6X4");
} else {
// here 'match' will be an array of 2 numeric values [D,D] where d is an integer.
}
}