Validating phone numbers. Null is not an object - javascript

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");

Related

Write a hasNoneLetters function

Write a hasNoneLetters function that takes 2 strings phrase and blacklist and returns true, if phrase does not contain any letters from blacklist, otherwise returns false.
Comparison should be case-insensitive, it means x inside blacklist does not allow using X.
Examples:
hasNoneLetters('Mate Academy', 'pqrs') === true;
hasNoneLetters('ABC', 'a') === false;
my answer was:
function hasNoneLetters(phrase, blacklist) {
if(phrase.includes(blacklist)) {
return true;
} else {
return false;
}
}
but one test didn't passed saying 'It should return true if no matching letters' mine returned false;
function hasNoneLetters(phrase, blacklist) {
const r = new RegExp(`[${blacklist}]`, 'i')
return Boolean(phrase.match(r))
}
console.log(hasNoneLetters('Mate Academy', 'pqrs'))
console.log(hasNoneLetters('ABC', 'a'))
By checking with the includes method, you're only looking if the string passed in arguments is contains inside the other string.
For example :
Phrase
blacklist
expected return
return value
Hello
hl
false
true
while your code was working for substrings like this
Phrase
blacklist
expected return
return value
Hello
hel
true
true
World
ld
true
true
To make the program work, you need to loop through all the characters and check if those are included in the string !
Example
function hasNoneLetters(phrase, blacklist) {
const letters = blacklist.split('')
for (const letter of letters){
if (phrase.includes(letter)) return false
}
return true
}
console.log(hasNoneLetters("Hello world", "ab")) // true
console.log(hasNoneLetters("Hello world", "abcd")) // false
Note : as #albjerto mentionned, you should also check with case sensitivity.
This can be done using the toLowerCase method on the phrase and the blacklist.
Example :
function hasNoneLetters(phrase, blacklist) {
const lowerPhrase = phrase.toLowerCase()
const lowerBlacklist = blacklist.toLowerCase()
const letters = lowerBlacklist.split('')
for (const letter of letters){
if (lowerPhrase.includes(letter)) return false
}
return true
}
console.log(hasNoneLetters("Hello world", "ab")) // true
console.log(hasNoneLetters("Hello world", "abcD")) // false
console.log(hasNoneLetters("HeLlO world", "O")) // false
You have to split the blacklist string into individual characters and compare every character in phrase with each upper- & lower-case character from blacklist. Something like this:
function hasNoneLetters(phrase, blacklist) {
let forbidden = blacklist.split('');
return forbidden.every(char => {
return !phrase.includes(char.toLowerCase()) && !phrase.includes(char.toUpperCase());
});
}
console.log('should be true', hasNoneLetters('Abracadabra', 'mstvz'));
console.log('should be false', hasNoneLetters('Abracadabra', 'c'));
You can just convert two strings params to either lowercase or uppercase and then loop over every character in the blacklist string
function hasNoneLetters(phrase, blacklist) {
blacklist.toLowerCase().split('').forEach(function(c) {
if(phrase.toLowerCase().includes(c) {
return true;
}
});
return false
}

Javascript RegularExpression is not working

If i am giving Special Symbol only at beginning then it's working otherwise it's not working.
For example:
var password = '#Sourav12345'
if (password.search(/[#_!#$%^&*()<>?/\|}{~:]/)) {
return true
}
else{
return false
}
If i will change password to Sourav#12345.it won't work .Plz. help me
Your regex should work perfectly fine, the issue you are probably encountering is that search() returns the index if the first matched occurencens found, otherwise -1.
So only your case where # is the first character will evalute to false in your condition. You would need to adapt your condition:
var password = 'Sourav12345#.it'
var search = password.search(/[#_!#$%^&*()<>?/\|}{~:]/);
if (search >= 0) {
console.log(true)
}
else{
console.log(false)
}
Or use a different mehtod to check against a regex like test()
var password = 'Sourav12345#.it'
var test = /[#_!#$%^&*()<>?/\|}{~:]/.test(password);
if (test) {
console.log(true)
} else {
console.log(false)
}
This is the correct regex:
/[#_!#$%^&*()<>?\/\|}{~:]/
Just escaped the "/" to make it work
The search() method searches a string for a specified value and returns the position of the match.
if it is not found it will return -1 else it returns the position number
var x='#Sourav12345'.search('/[#_!#$%^&*()<>?/\|}{~:]/') > 0?true:false;
console.log(x)

How to implement a function that will return when an intense string is passed in, and false otherwise?

Strings are intense if they end in three or more more ! marks. However, having ! marks anywhere but the end makes for a non-intense string.
The issue I'm having is when there is an ! in the middle of a string. The result should be false but it's still resulting as true.
My code:
function intenseString (str) {
if (str.slice(-3) !== "!!!") {
return false;
}
else if(str.slice(str.indexOf("!"))){
return false;
}
else if(str.slice(-3) === "!!!"){
return true
}
}
Use indexOf instead of slicing the string:
const strings = ['abc!!!', 'abc!!de', 'abc!']
const intenseString = (str, chars) => str.indexOf(chars) >= 0
console.log(strings.map(x => intenseString(x, '!!!')))
Here's your code, with some formatting tweaks for readability:
function intenseString(str) {
if (str.slice(-3) !== '!!!') {
return false;
}
if (str.slice(str.indexOf('!'))) {
return false;
}
if (str.slice(-3) === '!!!') {
return true;
}
}
Can you give some example inputs that return true? I don't think this will ever return true because the second if statement says "return false if there are any !'s in the string, which is implied by passing the first if.
I believe you meant to add + 1: if (str.slice(str.indexOf('!') + 1)) return false which says "return false if there are any !'s that are not the last character in the string", which still won't work: The first if statement will return false if the string doesn't end with !!! meaning that the smallest string that would get to the second if statement is !!! and there will always be characters after the first !.
Another potential attempt would be to only check the string before the last three characters if (str.slice(0, -3).slice(str.indexOf('!') + 1)) return false, which almost works except for strings containing more than 4 ! at the very end... (such as !!!!!).
I don't see a simple way (without regex to check that the remaining characters are only !) to make the second if statement work without looping over the string.
Note that your final if is unnecessary. Your first two are checking for failure and if they pass through them, it must be an intenseString. Also the string must end in !!! if it got past the first if.
Here's a potential solution which goes through every character in the string, except for the last 4, and returns false if there is ever an ! followed by something that is not an !.
function intenseString(str) {
if (!str.endsWith('!!!')) {
return false;
}
for (let i = 0; i < str.length - 4; i++) {
if (str.charAt(i) === '!' && str.charAt(i + 1) !== ('!')) {
return false;
}
}
return true;
}
Try one of these ways:
function intenseString(str) { return str.slice(-3) === '!!!'; }
function intenseString(str) { return str.endsWith('!!!'); }
function intenseString(str) { return /!{3}$/.test(str); }

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

regex check for only these carrot characters

What's the regex for just these characters <>. I was doing something like this which checks for to make sure only these are used.
function validateSpecialCharacters( value ){
var regex = /^\s*[a-zA-Z0-9,\s]+\s*$/;
return (regex.test(value)) ? true : false;
}
Instead I want to check if < or > is been used if so return true
Updated:
This is what I used in the end.
function validateCaretCharacters( value ){
var regex = /\<|\>/g;
return (regex.test(value)) ? false : true;
}
so now if I enter a < or a > in the input field along with other text or numbers it will catch it and return false meaning it's not valid. I probably should change the name of the function to something more meaningful.
Thanks for all the help.
.test will return either true or false, so you're essentially saying if true, then true, else false.
var regex = /<|>/g;
if(regex.test(val)){
// returned true - do something.
} else {
// returned false - do something else.
}
should work for you.

Categories

Resources