array.length never equals zero and halts the program - javascript

When no matches occur for a string, the length of that array does not equal 0 and it is impossible to craft a if else statement to allow for a false when there are no matches.
value is a multi-line input from a single textarea, token in this case is var token = "//num" defined in another function and passed in.
Here is my checking function:
function checkValid(value, token)
{
// Checks to see if value contains the token
var reg = new RegExp(token, "g");
var result = value.match(reg);
if (result.length == 1)
{
return true;
}
return false;
}
If the input text contains more than one instance of the token I get a false return, which is what I want, also a single occurrence of the token will return a true. But zero occurrences of the token will not allow any response. At this point I believe the program is halting but of course codepen gives no indication this is the case.

When no matches occur, match returns null rather than an empty array.
Check that result exists before checking result.length.
function checkValid(value, token)
{
// Checks to see if value contains the token
var reg = new RegExp(token, "g");
var result = value.match(reg);
return result && result.length;
}

.match() returns null if there is no match (see MDN's documentation), it doesn't return an empty array:
> 'aa'.match(new RegExp('a', 'g'))
[ 'a', 'a' ]
> 'a'.match(new RegExp('a', 'g'))
[ 'a' ]
> 'b'.match(new RegExp('a', 'g'))
null
You can then check if the result is null or not:
if (result === null) return false
or in a more compact way:
function checkValid(value, token)
{
var reg = new RegExp(token, "g");
var result = value.match(reg);
return (result !== null && result.length === 1);
}

Related

Check occurrence of element in string with Regex?

I have strings and some of them may contain : or =
I would like to find all cases, where these symbols occurs, but only once(!).
I wrote this code, which works, but would like to solve with Regex expression
function find(stringToCheck: string): string {
return stringToCheck.includes(':') &&
stringToCheck.split(':').length - 1 === 1
? ':'
: stringToCheck.includes('=') && stringToCheck.split('=').length - 1 === 1
? '='
: '';
}
The string is searched for matches with : or = which are then stored as a RegExp match array. The length of this array then matches how many instances of the string were found.
Where the RexExp objects are created the flag "g" is used to find all matches, rather than just the first one.
function find (stringToTest) {
const a = stringToTest.match(new RegExp(":", "g"));
const b = stringToTest.match(new RegExp("=", "g"));
if (a?.length > 1 || b?.length > 1) return true;
return false;
}
console.log(find("hello:world=")); // false
console.log(find("hello world")); // false
console.log(find("hello world====")); // true
Try this:
function find (stringToCheck)
{
return (/^[^:]*:[^:]*$/.test(stringToCheck) && /^[^=]*=?[^=]*$/.test(stringToCheck))||(/^[^:]*:?[^:]*$/.test(stringToCheck) && /^[^=]*=[^=]*$/.test(stringToCheck));
}
console.log(find("iron:man"));
console.log(find("iron=man"));
console.log(find("iron::man"));
console.log(find("iron==man"));
console.log(find("ironman"));
You could use:
^[^:=]*[:=][^:=]*$
function checkString(str){
return /^[^:=]*[:=][^:=]*$/.test(str);
}
console.log(checkString('Neither'));
console.log(checkString('One equal ='));
console.log(checkString('One colon :'));
console.log(checkString('colon equal :='));
console.log(checkString('Multiple = equal ='));
console.log(checkString('Multiple : colon :'));
console.log(checkString('Multiple = both : col=on :'));

Way to test empty length property for null and return a string?

I am working through a challenge and trying to set it up so in the event that you pass a string you can determine if there are between 2 and 4 of the letter argument in that string.
My testing of the function worked, however if the matched array is 0 length (in the event there are no matching letters in said string) there is no way to measure the length. I get the error : TypeError: Cannot read property 'length' of null
I tried using a conditional that would return a string if the length was null. Didn't work, I'm not sure if there is a way to funnel this error into a conditional. Any ideas?
TLDR: Is there a way catch to TypeError: Cannot read property 'length' of null before it throws an error?
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex);
if (matched.length == null) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
countLetters('Letter', 'e');
true
countLetters('Letter', 'r');
false
countLetters('Letter', 'z');
//TypeError: Cannot read property 'length' of null
If(matched == null || matched.length != 0)
You can try let matched = string.match(regex) || [];
matched.length == null will always be false, so try matched.length === 0
two changes required to make it work as you need:
handle null when no match is found
check for length appropriately
corrected code below:
function countLetters(string, letter) {
let regex = new RegExp(letter, 'g');
let matched = string.match(regex) || [];
if (matched.length == 0) {
return "There are no matching characters.";
} else {
let totalLetters = matched.length;
return (totalLetters >= 2 && totalLetters <= 4)? true : false;
}
}
i would strongly advise that you name your method appropriately. it isn't aligned with the return value or it's type. also, you return either string or a boolean value. one should refrain from that. return values of the same type irrespective of whether a match is found or otherwise.

Validating phone numbers. Null is not an object

I'm doing a challenge on Freecodecamp. I'm having a problem that seems to make no sense to me.
function telephoneCheck(str) {
// if string contains a letter then return false //
var exc = /[a-z\?/]/;
// check str to see if it has anything from the //
// regex and then make it into a string. //
var excJoin = str.match(exc).join('');
// if theres something in the //
// variable(something was found with regex) //
// then return false //
if(excJoin.length > 0) {
return false;
}
// else return true //
if(excJoin === null){return true;}
}
telephoneCheck("2(757)622-7382");
Returning false is fine, however when I just want to say else {return true;} it tells me null is not an object. What's the problem?
http://freecodecamp.com/challenges/validate-us-telephone-numbers
String.prototype.match (in your code: str.match(exc)) returns null if it didn't match the regex, so then the code is equivalent to null.join(''), which is an error.
Instead, check if it's null first:
var excResult = str.match(exc);
if (excResult === null) {
// didn't match, do something
} else {
// did match, do something else
}
You must test for nullity before using the object
str.match(exc) returns null if there are no founds for the given pattern.
So your code should do this:
function telephoneCheck(str) {
// if string contains a letter then return false
var exc = /[a-z\?/]/;
//The match() method retrieves the matches when matching a string against a regular expression.
var excResult= str.match(exc);
//return false if there is a found
if(excResult != null) {
return false;
}
else{
//there is no found cause excResult == null
return true;
}
telephoneCheck("2(757)622-7382");

Check if entries are seperated by comma

I have several strings that contain entries separated by a comma, for example:
('ENTRY1', 'ENTRY2','ENTRY3')
As you can see, each entry is separated by a comma, either with or without a following blank.
How can I check with JavaScript if between each entry there is always a comma (with or without a blank).
The string can contain 0 to n entries.
Requirement: A script should return true or false based on the following example:
('ENTRY1', 'ENTRY2','ENTRY3') // return false
('ENTRY1' 'ENTRY2''ENTRY3') // return true
('ENTRY1','ENTRY2''ENTRY3') // return true
false = correct entry
true = false entry
From your example:
('ENTRY1', 'ENTRY2','ENTRY3') // return false
('ENTRY1' 'ENTRY2''ENTRY3') // return true
('ENTRY1','ENTRY2''ENTRY3') // return true
Since entry is enclosed within single quote (' '), you can do
function validate(entries) {
if (entries.replace(/ /g, '').indexOf("''") > -1) {
return true;
} else {
return false;
}
}
//Test case
var entries1 = "('ENTRY1', 'ENTRY2','ENTRY3')";
var entries2 = "('ENTRY1' 'ENTRY2''ENTRY3')";
var entries3 = "('ENTRY1','ENTRY2''ENTRY3')";
document.write(validate(entries1)+","+validate(entries2)+","+validate(entries3));
You could use split like this:
var splitArray = someString.split(',');
for explicitly stating its separated by a ,
If I understand this correctly,
you can use regex for this to make sure there's always a comma between two items if your string is exactly as you mention above
var str = "('ENTRY1', 'ENTRY2','ENTRY3')";
str = str.match(/'([^'])+'/g).join(',');
since you updated your code you can use this code to achieve following
('ENTRY1', 'ENTRY2','ENTRY3') // return false
('ENTRY1' 'ENTRY2''ENTRY3') // return true
('ENTRY1','ENTRY2''ENTRY3') // return true
false = correct entry true = false entry
function isNotOK(str){
var match = str.match(/'[^,i]+'/g);
var len = str.match(/'([^'])+'/g)
if(match && len && match.length === len.length){
return false;
}
return true;
}
var str1 = "('ENTRY1', 'ENTRY2','ENTRY3')";
var str2 = "('ENTRY1' 'ENTRY2''ENTRY3')";
document.write(isNotOK(str1) + ' , ' + isNotOK(str2));

Use javascript to return true if a string contains an exact match

I've been using the .indexOf('') > -1 in order to check whether there's a match in a string. The problem that I'm having is that when I'm performing the match on multiple strings, I get a match on the string for both EIFT and EI (since EIFT contains EI), and so the function returns true for both sentences. What I need is a way for this to only return true for function eIft if the string is "EIFT", but not for EI.
My current code is as follows, and I've been trying to think of ways around this but haven't had any success yet.
function eI(mystring){
return mystring.indexOf("EI") > -1
}
function eIft(mystring){
return mystring.indexOf("EIFT") > -1
}
Thanks!
You can use ===; that will do an exact match of strings. Use indexOf only if you're checking whether the string contains another string.
function eI (mystring) {
return mystring === "EI";
}
function eIFt(mystring) {
return mystring === "EIFT";
}
If you are checking inside a string for you values (e.g. heleilo), then you need to confirm your positive results for the 'EI' check:
function eI(mystrng) {
return mystring.indexOf("EI") != -1 && !eIFt(mystring);
}
This would only work provided they don't both exist in different occurences (e.g. heleileifto). In this case, you have to check the immediate following characters:
function eI(mystring) {
var pos = mystring.indexOf("EI");
if (pos != -1) { // found
var char1 = mystring[pos + 2];
var char2 = mystring[pos + 3];
return char1 !== 'F' && char2 !== 'T';
}
}
OR
function eI(mystring) {
var pos = mystring.indexOf("EI");
if (pos != -1) { // found
return pos != eIFt(mystring); // they won't have the same index
}
}

Categories

Resources