Check for empty string is failing in js - javascript

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]+/);

Related

How to write text within a box p5.js

hopefully this is a silly mistake but I am trying to write text within a rect in p5.js. My method was to convert the text to a character array and count the number of characters I am printing before increasing a y-offset to step down a line. Here is the example code:
let splitQuote = tweetsTable.getRow(row).get("Quote").split('');
let size = splitQuote.length;
let rtnQuoteLines;
let yOff =0;
for (i=0;i<size;i++) {
rtnQuoteLines += splitQuote.shift();
if (i % 44 == 0 && i > 0) {
let rtn = rtnQuoteLines.toString();
text(rtn, 1100,yOff);
console.log("rtn: "+rtn);
yOff += 250;
rtnQuoteLines = "";
} else if (splitQuote.length < 44) {
let rtn = splitQuote.toString();
console.log("rtn2: "+rtn);
text(rtn, 1100,yOff);
break;
}
}
The console output makes me think I'm making some mistake too because the end of the quote remains an array and the start of the quote has 'undefined' before the first character.
Can anyone spot my mistake or suggest a neater way of doing this?
Thanks in advance for your help
First off, to stop the undefined at the begin, set let rtnQuoteLines = ""; When it is initally printed it will have a value to print.
You are getting all of the commas seen in the last part of your console log because when convert an array to a string it will automatically seperate eact element with commas. To make avoid this use let rtn = splitQuote.join(""); instead.
Hope this helps! :D

Javascript and Regex: undefined and ""

I am not really familiar with Regular Expressions and I am having the following problem:
When running the regExp to split my string I get lots of undefined and "" along with the result. I already tried to use "(?:" which I saw in another answer here in stackoverflow and lots of other things.
I am then using the array.filter function to remove them but I didn`t want to do that. Can anyone help me? (and also explain to me why this is happening).
let values = line.split(/(\!=)|(<=)|(>=)|(==)|(\/\/)|(\/\*)|(\*\/)|(")|(=)|(<)|(>)|(\+)|(-)|(\*)|(\\)|(\()|(\))|;| /g);
return values.filter(value => {
return value !== undefined && value !== "";
});
Strings that can be used:
"int x = 7;" => ["int","x","=","7",";"]
"int x = 7 + 25 * 52" => ["int","x","=","7","+","25","*","52"]
"while( x != 0)" => ["while","(","x","!=","0",")"]
'if(idade > 70 && sexo == "masculino")'
=> ["if","(","idade",">","70","&&","sexo","==",""masculino"",")"]
Thanks!
The reason is that you have each alternative in its own capture group. Only the capture group that actually matches will be filled in, the rest will be empty. Instead, put the capture group around all the alternatives.
line = "#include <stdio.h>";
let values = line.split(/(\!=|<=|>=|==|\/\/|\/\*|\*\/|"|=|<|>|\+|-|\*|\\|\(|\)|;| )/g);
console.log(values);

Solving a 4x4 (simplified one) sudoku in javascript

I have a problem where I have to code an automatic solution to a given sudoku which is 4x4 which means the numbers go only as far 1 2 3 4. It's a simplified version of a sudoku since I am still new to programming.
I have a given template with random sudoku generated from it and I have to write a code to solve the sudoku automatically.
Here is what I have in the begining as sudoku that i have to solve
sudoku[6] = [[" ","2"," "," "],
[" "," ","2"," "],
[" "," "," ","3"],
["4"," "," "," "]
My idea was to insert "1234" into empty " " and then remove the numbers from "1234" when one of the numbers is already present in the column, row and quadrant. So what I wanted to do is with the use of loops go through all the positions in the tables and the moment I find for example "1" alone i will remove the 1 from "1234".
Here is the beggning of my code, it appears it doesnt work the moment I reach if, can you guys please tell me what I am doing wrong or why isn't it working when i get to my If.
Thank you in advance.
var sudoku = sudoku[6];
// function to put "1234" into empty space ""
var concatenate = function (s)
{
for (i=0; i<s.length; i++)
for (j=0; j<s.length; j++)
if (sudoku[i][j] === " ")
sudoku[i][j] = "1234";
};
concatenate(sudoku);
// function to solve the sudoku automatically.
var solve = function (t)
{
for (i = 0; i<t.length; i++)
for (j=0; j<t.length; j++)
for (k=j; k<(4+j); k++)
if (sudoku[i][j].length === 1) // this is where it seems to bug, in this if im trying to find the position where we only have one number and not "1234"
var s = sudoku[i][j];
if (sudoku[i][k-j] !== ("1" || "2" || "3" || "4")) // here im finding the position of all position in the sudoku where ive got "1234" so i can remove the number found in the previous if.
{
var index = sudoku[i][k-j].indexOf(s);
var string_new = sudoku[i][k-j].substring(0,index) + sudoku[i][k-j].substring(index+1, 4);
sudoku[i][k-j] = string_new;
}
};
There are known algorithms to solve the sudoku problem, you should take a look.
For such a small sudoku like yours, you may choose to implement not taking in account the computational time. (choose the simplest to implement)
For more infos: Sudoku solving algorithms
Reguarding your code, the idea (on paper) is not bad, but I really can't understand what you intended to do with that. For example:
if (sudoku[i][k-j] !== ("1" || "2" || "3" || "4"))
This line has no sense. The expression ("1" || "2" || "3" || "4") will always evaluates "1". So you are writing:
if (sudoku[i][k-j] !== "1")
Moreover sudoku[i][k-j] is a string containing "1234" (or part of it), so you should use indexOf to check the presence of a character.
And what is the use of the internal for?
for (k=j; k<(4+j); k++)
Why are you iterating from j to 4+j? You're always using k-j to access the variable (sudoku[i][k-j]), that is always between j-j and 4+j-j. So why don't:
for (k=0; k<4; k++)
There are more other logic errors in you code...
If you want to implement that idea, you should take your time to think what you are writing, or (better) use a known algorithm.
You should replace this one:
if (sudoku[i][k-j] !== ("1" || "2" || "3" || "4"))
to something like this:
if ( sudoku[i][k-j] !== "1" || sudoku[i][k-j] !== "2" || ...
or you can consider using a switch statement also, but I'm not sure if it's gonna solve the bug that you're struggling with that or not ...

Why doesnt this Javascript regular expression work

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)){

Removing a string return after a function has been processed

I'm a beginner and a student and I'm hoping someone can help me out. I have an assignment where I need the program to be broken up into 3 functions. The first takes a sentence from the user, the second converts the sentence into a new "pig language" depending on the length of each word, and the third displays the results in the console. I have the heart of this program done, but I have a problem with clearing out the return string. Specifically, once the user has gone through all 3 steps, I don't want them to be able to enter into the 3rd part of the program and see the results again. I want them to have to go back to the beginning. Sorry for drawing this out so much, but I'm just not sure of how else to explain it.
Here's my code:
function prog1(){
var userLang = prompt("Type in your sentence");
//If the user enters an empty string
if(userLang == ""){
console.log("You must enter a sentence");
}
//If the user presses cancel
else if(userLang == null){
wantToQuit = true;
}
//If the user enters in a good string
else {
console.log("Thank you, now go to program 2");
been2prog1 = true;
return userLang;
}
}
function prog2(){
//sets newLang = userLang and splits the string
var newLang = prog1Lang.split(" ");
//enters loop to find length of each split word
var x = 0;
for( x = 0; x < newLang.length; x++ ){
//if it's 5 or less words, add -oink
if ((newLang[x].length) <= 5){
newLang[x] += "-oink";
}
//if it's more than 5 words, add -a
else {
newLang[x] += "-a";
}
}
**newLang.join(" ");**
//put the string back together
console.log("String converted");
been2prog2 = true;
return newLang;
}
function prog3(){
var endLang = prog2Lang;
console.log(endLang);
**delete prog2Lang;**
}
I was thinking "delete" might work, as seen above, but I didn't do anything all all. Then I was thinking a Boolean, but I am not sure how to go about doing so. Any help would be much appreciated.
One last thing, I am also stuck on how to join my string back together. Currently it logs it in the console as being a part of the array and separates each word with quotes and a comma. I've looked up the .join(); and I thought it would do the trick, but it doesn't seem to work either. I put it inside of the if else statements in function 2 but, it just freaks out when I do that, so pointers on this issue would also be much appreciated.
Thank you!
Try assigning the newLang.join to itself..
newLang = newLang.join(" ");
I wasn't sure what the other bit was that you were having trouble with was, I was a bit confused.
if all you are trying to do is clear out a string variable then..
prog2Lang = null;
or
prog2Lang = "";
null is a null object and "" is an empty string.
Is that what you were after?

Categories